Example #1
0
    def set_language(self, headers):
        '''Invoke before everything else. And set the translation language'''
        languages = headers.get('Accept-Language', '')

        found_lang = False

        for match in accept_language_regexp.finditer(languages):
            # make sure we have a correct language code format
            language = match.group(1)
            if not language:
                continue
            language = language.replace('_', '-').lower()

            # en is the default language
            # Fix borked language detection in some browsers.
            if language.split('-')[0] in ['en', 'en-gb', 'en-GB']:
                found_lang = True
                break

            try:
                # set_lang needs a locale name formed parameter
                set_lang(language.replace('-', '_'))
                found_lang = True
                break
            except LanguageError:
                log.debug(
                    "Cannot set requested language: %s. Trying next language if available.",
                    language)

        if not found_lang and languages:
            log.warning("Cannot set preferred language: %r" % languages)

        return
Example #2
0
    def __before__(self):
        """
        __before__ is called before controller methods and after __call__
        """
        # on each call propagate settings calls into global settings.
        set_rhodecode_config(config)
        attach_context_attributes(c)

        # TODO: Remove this when fixed in attach_context_attributes()
        c.repo_name = get_repo_slug(request)  # can be empty

        self.cut_off_limit_diff = safe_int(config.get('cut_off_limit_diff'))
        self.cut_off_limit_file = safe_int(config.get('cut_off_limit_file'))
        self.sa = meta.Session
        self.scm_model = ScmModel(self.sa)

        default_lang = c.language
        user_lang = c.language
        try:
            user_obj = self._rhodecode_user.get_instance()
            if user_obj:
                user_lang = user_obj.user_data.get('language')
        except Exception:
            log.exception('Failed to fetch user language for user %s',
                          self._rhodecode_user)

        if user_lang and user_lang != default_lang:
            log.debug('set language to %s for user %s', user_lang,
                      self._rhodecode_user)
            translation.set_lang(user_lang)
Example #3
0
    def set_language(self):
        '''Invoke before everything else. And set the translation language'''
        languages = request.headers.get('Accept-Language', '').split(';')
        found_lang = False

        for language in languages:
            for lang in language.split(','):
                try:
                    # Fix borked language detection on some browsers.
                    if lang == "en" or lang == "en-gb" or lang == "en-GB":
                        found_lang = True
                        break
                    set_lang(lang)
                    found_lang = True
                    break
                except LanguageError as exx:
                    pass

            if found_lang is True:
                break

        if found_lang is False:
            log.warning("Cannot set preferred language: %r" % languages)

        return
Example #4
0
    def set_language(self, headers):
        '''Invoke before everything else. And set the translation language'''
        languages = headers.get('Accept-Language', '')

        found_lang = False

        for match in accept_language_regexp.finditer(languages):
            # make sure we have a correct language code format
            language = match.group(1)
            if not language:
                continue
            language = language.replace('_', '-').lower()

            # en is the default language
            # Fix borked language detection in some browsers.
            if language.split('-')[0] in ['en', 'en-gb', 'en-GB']:
                found_lang = True
                break

            try:
                # set_lang needs a locale name formed parameter
                set_lang(language.replace('-','_'))
                found_lang = True
                break
            except LanguageError:
                log.debug("Cannot set requested language: %s. Trying next language if available.",
                          language)

        if not found_lang and languages:
            log.warning("Cannot set preferred language: %r" % languages)

        return
Example #5
0
    def set_language(self):
        '''Invoke before everything else. And set the translation language'''
        languages = request.headers.get('Accept-Language', '').split(';')
        found_lang = False

        for language in languages:
            for lang in language.split(','):
                try:
                    # Fix borked language detection on some browsers.
                    if lang == "en" or lang == "en-gb" or lang == "en-GB":
                        found_lang = True
                        break
                    set_lang(lang)
                    found_lang = True
                    break
                except LanguageError as exx:
                    pass

            if found_lang is True:
                break

        if found_lang is False:
            log.warning("Cannot set preferred language: %r" % languages)

        return
Example #6
0
    def set_language(self, headers):
        '''Invoke before everything else. And set the translation language'''
        languages = headers.get('Accept-Language', '')

        found_lang = False

        for match in accept_language_regexp.finditer(languages):
            # make sure we have a correct language code format
            language = match.group(1)
            if not language:
                continue
            language = language.replace('_', '-').lower()

            # en is the default language
            if language.split('-')[0] == 'en':
                found_lang = True
                break

            try:
                set_lang(language.split('-')[0])
                found_lang = True
                break
            except LanguageError:
                log.debug(
                    "Cannot set requested language: %s. Trying next"
                    " language if available.", language)

        if not found_lang and languages:
            log.warning("Cannot set preferred language: %r", languages)

        return
Example #7
0
    def set_language(self, headers):
        '''Invoke before everything else. And set the translation language'''
        languages = headers.get('Accept-Language', '').split(';')

        found_lang = False

        for language in languages:
            for lang in language.split(','):
                try:
                    if lang[:2] == "en":
                        found_lang = True
                        break
                    if lang == 'de':
                        pass
                    set_lang(lang)
                    found_lang = True
                    break
                except LanguageError as exx:
                    pass

            if found_lang is True:
                break

        if found_lang is False:
            log.warning("Cannot set preferred language: %r" % languages)

        return
Example #8
0
    def set_language(self, headers):
        '''Invoke before everything else. And set the translation language'''
        languages = headers.get('Accept-Language', '')

        found_lang = False

        for match in accept_language_regexp.finditer(languages):
            # make sure we have a correct language code format
            language = match.group(1)
            if not language:
                continue
            language = language.replace('_', '-').lower()

            # en is the default language
            if language.split('-')[0] == 'en':
                found_lang = True
                break

            try:
                set_lang(language.split('-')[0])
                found_lang = True
                break
            except LanguageError:
                log.debug("Cannot set requested language: %s. Trying next"
                          " language if available.", language)

        if not found_lang and languages:
            log.warning("Cannot set preferred language: %r", languages)

        return
Example #9
0
 def __before__(self):
     "before"
     languages = [lang.split('-')[0] for lang in request.languages
     if check_language(lang.split('-')[0])]
     set_lang(languages)
     if 'lang' in session:
         set_lang(session['lang'])
     self.invalidate = request.GET.get('uc', None)
Example #10
0
    def __before__(self, language="en"):
        c.title = _("Midgard CMS")

        h.header.addMeta(name="generator", value="MidgardPyMVC")

        if language:
            set_lang(language)

        c.language = language
Example #11
0
 def __before__(self):
     "before"
     languages = [
         lang.split('-')[0] for lang in request.languages
         if check_language(lang.split('-')[0])
     ]
     set_lang(languages)
     if 'lang' in session:
         set_lang(session['lang'])
     self.invalidate = request.GET.get('uc', None)
Example #12
0
  def setLang(self):
    if (not 'lang' in request.params):
      redirect(url(controller='members', action='showAllMembers'))

    if request.params['lang'] in ('en', 'lb', 'de'):
      session['language'] = request.params['lang']
      session.save()
      set_lang(request.params['lang'])

    redirect(url(controller='members', action='showAllMembers'))
Example #13
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        c.lang = environ['pylons.routes_dict'].get('_lang')
        if c.lang:
            set_lang(c.lang)

        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            meta.Session.remove()
Example #14
0
 def __before__(self):
     "before"
     if 'theme' not in session:
         session['theme'] = ''
         basedir = config.get('baruwa.themes.base', None)
         if basedir:
             # Default theme
             defaultdir = os.path.join(basedir, 'templates', 'default')
             if os.path.exists(defaultdir):
                 session['theme'] = 'default'
             # Host theme
             themedir = os.path.join(basedir, 'templates',
                                     request.server_name)
             if os.path.exists(themedir):
                 session['theme'] = request.server_name
         session.save()
     self.theme = session.get('theme')
     if 'lang' in session:
         set_lang(session['lang'])
     else:
         try:
             languages = [
                 lang.split('-')[0] for lang in request.languages
                 if check_language(lang.split('-')[0])
             ]
             set_lang(languages)
         except AttributeError:
             default_lang = config.get('baruwa.default.language', 'en')
             if check_language(default_lang):
                 set_lang([default_lang])
             else:
                 set_lang(['en'])
     # pylint: disable-msg=W0201
     self.invalidate = request.GET.get('uc', None)
     self.langchange = request.GET.get('lc', None)
Example #15
0
  def __call__(self, environ, start_response):
    """Invoke the Controller"""
    # WSGIController.__call__ dispatches to the Controller method
    # the request is routed to. This routing information is
    # available in environ['pylons.routes_dict']
    if 'language' in session and session['language'] in self.languages:
      set_lang(session['language'])
    else:
      set_lang(self.default_language)

    try:
      return WSGIController.__call__(self, environ, start_response)
    finally:
      Session.remove()
Example #16
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        c.lang = environ['pylons.routes_dict'].get('_lang')
        if c.lang:
            set_lang(c.lang)

        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            meta.Session.remove()
Example #17
0
 def __before__(self):
     "before"
     if 'theme' not in session:
         session['theme'] = ''
         basedir = config.get('baruwa.themes.base', None)
         if basedir:
             # Default theme
             defaultdir = os.path.join(basedir, 'templates', 'default')
             if os.path.exists(defaultdir):
                 session['theme'] = 'default'
             # Host theme
             themedir = os.path.join(basedir, 'templates',
                         request.server_name)
             if os.path.exists(themedir):
                 session['theme'] = request.server_name
         session.save()
     self.theme = session.get('theme')
     if 'lang' in session:
         set_lang(session['lang'])
     else:
         try:
             languages = [lang.split('-')[0] for lang in request.languages
                     if check_language(lang.split('-')[0])]
             set_lang(languages)
         except AttributeError:
             default_lang = config.get('baruwa.default.language', 'en')
             if check_language(default_lang):
                 set_lang([default_lang])
             else:
                 set_lang(['en'])
     # pylint: disable-msg=W0201
     self.invalidate = request.GET.get('uc', None)
     self.langchange = request.GET.get('lc', None)
Example #18
0
 def test_noop(self):
     import pylons
     from pylons.i18n.translation import _, N_, set_lang
     foo = N_('Hello')
     class Bar(object):
         def __init__(self):
             self.local_foo = _(foo)
     
     assert Bar().local_foo == 'Hello'
     
     t = set_lang('fr', set_environ=False, pylons_config=lang_setup)
     pylons.translator._push_object(t)
     assert Bar().local_foo == 'Bonjour'
     t = set_lang('es', set_environ=False, pylons_config=lang_setup)
     pylons.translator._push_object(t)
     assert Bar().local_foo == u'¡Hola!'
     assert foo == 'Hello'
Example #19
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']
        try:
            if 'lang' in session:
                try:
                    set_lang(session['lang'])
                except LanguageError:
                    # remove lang from session if an error occured
                    del session['lang']
                    session.save()

            return WSGIController.__call__(self, environ, start_response)
        finally:
            meta.Session.remove()
Example #20
0
    def test_noop(self):
        import pylons
        from pylons.i18n.translation import _, N_, set_lang
        foo = N_('Hello')

        class Bar(object):
            def __init__(self):
                self.local_foo = _(foo)

        assert Bar().local_foo == 'Hello'

        t = set_lang('fr', set_environ=False, pylons_config=lang_setup)
        pylons.translator._push_object(t)
        assert Bar().local_foo == 'Bonjour'
        t = set_lang('es', set_environ=False, pylons_config=lang_setup)
        pylons.translator._push_object(t)
        assert Bar().local_foo == u'¡Hola!'
        assert foo == 'Hello'
Example #21
0
    def __before__(self):
        if "lang" in request.params and self._isLangAvailable(request.params.getone("lang")):
            lang = request.params.getone("lang")
            session["lang"] = lang

        if "lang" not in session:
            # get from user agent
            for language in request.languages:
                lang = language[0:2]
                if self._isLangAvailable(lang):
                    session["lang"] = lang
                    break

        if "lang" in session:
            try:
                set_lang(session["lang"])
            except LanguageError:
                # remove lang from session if an error occured
                del session["lang"]
            session.save()
Example #22
0
    def __before__(self):
        if 'lang' in request.params and self._isLangAvailable(
                request.params.getone('lang')):
            lang = request.params.getone('lang')
            session['lang'] = lang

        if 'lang' not in session:
            # get from user agent
            for language in request.languages:
                lang = language[0:2]
                if self._isLangAvailable(lang):
                    session['lang'] = lang
                    break

        if 'lang' in session:
            try:
                set_lang(session['lang'])
            except LanguageError:
                # remove lang from session if an error occured
                del session['lang']
            session.save()
Example #23
0
    def edit_information(self, language):
        if language is None:
            country = c.user.location.get_country()
            if country is not None:
                default_lang = country.language.id
            else:
                default_lang = c.lang

            redirect(url(controller='profile', action='edit_information',
                         lang=default_lang))

        version = c.user.general_info.get_version(language)
        if version is not None and version.text:
            defaults = { 'general_info_text': version.text,
                         'language': language.id }
        else:
            set_lang(language.id) # XXX cheap language switch
            template = render('profile/teacher/information_template.mako')
            set_lang(c.lang) # restore language
            defaults = { 'general_info_text': template,
                         'language': language.id }
            c.edit_template = True
        return htmlfill.render(self._edit_information_form(language), defaults=defaults)
Example #24
0
 def __before__(self):
     "before"
     if 'lang' in session:
         set_lang(session['lang'])
     else:
         try:
             languages = [lang.split('-')[0] for lang in request.languages
                     if check_language(lang.split('-')[0])]
             set_lang(languages)
         except AttributeError:
             default_lang = config.get('baruwa.default.language', 'en')
             if check_language(default_lang):
                 set_lang([default_lang])
             else:
                 set_lang(['en'])
     self.invalidate = request.GET.get('uc', None)
     self.langchange = request.GET.get('lc', None)
Example #25
0
    def set_language(self, headers):
        '''Invoke before everything else. And set the translation language'''
        languages = headers.get('Accept-Language', '').split(';')
        found_lang = False

        for language in languages:
            for lang in language.split(','):
                try:
                    if lang[:2] == "en":
                        found_lang = True
                        break
                    set_lang(lang)
                    found_lang = True
                    break
                except LanguageError as exx:
                    pass

            if found_lang is True:
                break

        if found_lang is False:
            log.warning("Cannot set preferred language: %r" % languages)

        return
Example #26
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']
        from pylons.i18n.translation import set_lang
        set_lang(environ['pylons.routes_dict']['_lang'])
        
        #figure out which map to display based on geoloc
        from pygeoip import GeoIP
        gi = GeoIP('/usr/share/GeoIP/GeoIP.dat') #GeoIP.GEOIP_MEMORY_CACHE)
        country_code = gi.country_code_by_addr(str(environ['REMOTE_ADDR']))
        #raise Exception('%s from %s'%(country_code,environ['REMOTE_ADDR']))
        if not country_code or country_code.lower() in ['a2']: 
            country_code = config['global_conf']['default_country']
        country_code=country_code.lower()

        c.use_google_maps,c.freemap_url = freemap_url_from_country(country_code)


        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            meta.Session.remove()
    def test_mapping(self):

        # multilang requires lang to be set
        from pylons.i18n.translation import set_lang, get_lang
        import pylons
        class dummyreq(object):
            class p(object):
                translator = object()
            environ = {'pylons.pylons': p()}
        pylons.request = dummyreq()
        pylons.translator.pylons_lang = ['en_GB']
        set_lang('en_GB')
        assert get_lang() == ['en_GB']

        assert 'dcatapit_theme_group_mapper' in config['ckan.plugins'], "No dcatapit_theme_group_mapper plugin in config"
        contents = self._get_file_contents('dataset.rdf')

        p = RDFParser(profiles=['it_dcat_ap'])

        p.parse(contents)
        datasets = [d for d in p.datasets()]
        eq_(len(datasets), 1)
        package_dict = datasets[0]


        user = User.get('dummy')
        
        if not user:
            user = call_action('user_create',
                               name='dummy',
                               password='******',
                               email='*****@*****.**')
            user_name = user['name']
        else:
            user_name = user.name
        org = Group.by_name('dummy')
        if org is None:
            org  = call_action('organization_create',
                                context={'user': user_name},
                                name='dummy',
                                identifier='aaaaaa')
        existing_g = Group.by_name('existing-group')
        if existing_g is None:
            existing_g  = call_action('group_create',
                                      context={'user': user_name},
                                      name='existing-group')

        context = {'user': '******',
                   'ignore_auth': True,
                   'defer_commit': False}
        package_schema = schema.default_create_package_schema()
        context['schema'] = package_schema
        _p = {'frequency': 'manual',
              'publisher_name': 'dummy',
              'extras': [{'key':'theme', 'value':['non-mappable', 'thememap1']}],
              'groups': [],
              'title': 'dummy',
              'holder_name': 'dummy',
              'holder_identifier': 'dummy',
              'name': 'dummy',
              'notes': 'dummy',
              'owner_org': 'dummy',
              'modified': datetime.now(),
              'publisher_identifier': 'dummy',
              'metadata_created' : datetime.now(),
              'metadata_modified': datetime.now(),
              'guid': unicode(uuid.uuid4),
              'identifier': 'dummy'}
        
        package_dict.update(_p)
        config[DCATAPIT_THEME_TO_MAPPING_SOURCE] = ''
        package_data = call_action('package_create', context=context, **package_dict)

        p = Package.get(package_data['id'])

        # no groups should be assigned at this point (no map applied)
        assert {'theme': ['non-mappable', 'thememap1']} == p.extras, '{} vs {}'.format(_p['extras'], p.extras)
        assert [] == p.get_groups(group_type='group'), 'should be {}, got {}'.format([], p.get_groups(group_type='group'))

        package_data = call_action('package_show', context=context, id=package_data['id'])

        # use test mapping, which replaces thememap1 to thememap2 and thememap3
        test_map_file = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'examples', 'test_map.ini')
        config[DCATAPIT_THEME_TO_MAPPING_SOURCE] = test_map_file

        package_dict['theme'] = ['non-mappable', 'thememap1']

        expected_groups_existing = ['existing-group']
        expected_groups_new = expected_groups_existing + ['somegroup1', 'somegroup2']
        expected_groups_multi = expected_groups_new + ['othergroup']

        package_dict.pop('extras', None)
        p = Package.get(package_data['id'])
        context['package'] = p 

        package_data = call_action('package_update',
                                   context=context,
                                   **package_dict)
        
        #meta.Session.flush()
        #meta.Session.revision = repo.new_revision()

        # check - only existing group should be assigned
        p = Package.get(package_data['id'])
        groups = [g.name for g in p.get_groups(group_type='group')]

        assert expected_groups_existing == groups, (expected_groups_existing, 'vs', groups,)

        config[DCATAPIT_THEME_TO_MAPPING_ADD_NEW_GROUPS] = 'true'


        package_dict['theme'] = ['non-mappable', 'thememap1']
        package_data = call_action('package_update', context=context, **package_dict)


        meta.Session.flush()
        meta.Session.revision = repo.new_revision()

        # recheck - this time, new groups should appear
        p = Package.get(package_data['id'])
        groups = [g.name for g in p.get_groups(group_type='group')]

        assert len(expected_groups_new) == len(groups), (expected_groups_new, 'vs', groups,)
        assert set(expected_groups_new) == set(groups), (expected_groups_new, 'vs', groups,)

        package_dict['theme'] = ['non-mappable', 'thememap1', 'thememap-multi']
        package_data = call_action('package_update', context=context, **package_dict)

        meta.Session.flush()
        meta.Session.revision = repo.new_revision()

        # recheck - there should be no duplicates
        p = Package.get(package_data['id'])
        groups = [g.name for g in p.get_groups(group_type='group')]

        assert len(expected_groups_multi) == len(groups), (expected_groups_multi, 'vs', groups,)
        assert set(expected_groups_multi) == set(groups), (expected_groups_multi, 'vs', groups,)

        package_data = call_action('package_update', context=context, **package_dict)

        meta.Session.flush()
        meta.Session.revision = repo.new_revision()

        # recheck - there still should be no duplicates
        p = Package.get(package_data['id'])
        groups = [g.name for g in p.get_groups(group_type='group')]

        assert len(expected_groups_multi) == len(groups), (expected_groups_multi, 'vs', groups,)
        assert set(expected_groups_multi) == set(groups), (expected_groups_multi, 'vs', groups,)

        meta.Session.rollback()
Example #28
0
 def transtest(self):
     set_lang('he')
     return _('Missing value')
Example #29
0
    def __before__(self):
        
        # If this is a multiple call to base then abort
        # Result is always set, so if it is not set then we know this is first call
        # This is needed because methods like member_actions.py:groups calls members.py:index. This would trigger 2 calls to base
        if hasattr(c, 'result'):
            return
        
        # AllanC - useful for debug
        #from pylons import session
        #print ""
        #print "CALL"
        #print request.environ.get("pylons.routes_dict")
        #print "GET"
        #print request.GET
        #print "POST"
        #print request.POST
        #print "SESSION"
        #print session
        #print "COOKIES"
        #print request.cookies
        
        # Setup globals variables ----------------------------------------------
        c.result = action_ok()  # Default return object
        
        # Request global - have the system able to easly view request details as globals
        current_request = request.environ.get("pylons.routes_dict")
        c.controller = current_request.get("controller")
        c.action     = current_request.get("action")
        c.id         = current_request.get("id")        
        #print "controller=%s action=%s id=%s" % (c.controller, c.action, c.id)
        
        c.format                   = current_request.get("format") or "html"
        c.subformat                = get_subdomain_format()
        c.auto_format_top_call     = False # Used as a flag to the auto_formatter to only output the top level decorator
        
        c.authenticated_form       = None # if we want to call a controler action internaly from another action we get errors because the auth_token is delted, this can be set by the authenticated_form decorator so we allow subcall requests
        c.web_params_to_kwargs     = None
        c.html_action_fallback_url = None # Some actions like 'follow' and 'accept' do not have templates - a fallback can be set and @auto_format interperits this as a redirect fallback
        c.host                     = request.environ.get('HTTP_HOST', request.environ.get('SERVER_NAME'))
        c.etag_master_generated    = False

        request.environ['app_version'] = app_globals.version
        request.environ['node_name']   = platform.node()

        
        # Detect and redirect to mobile ----------------------------------------
        #
        # For development we cant fake a subdomain call when acessing 127.0.0.1 :(
        # In the same way as we toggle_cache we can toogle_force_mobile
        # or
        # We detect that the host is an ip address and enable mobile subdomain if mobile
        if request.environ.get('is_mobile') and request.environ.get("HTTP_HOST", "").replace(".","").isdigit():
            log.debug('local mobile detected - auto mobile subdomain')
            c.subformat = 'mobile'
        elif cookie_get("force_mobile") and not cookie_get('force_web'):
            log.debug('force_mobile cookie present')
            c.subformat = 'mobile'
        # If we are not forcing mobile - attempt to redirect first time mobile viewers to the correct subdomain
        # Redirect to mobile site if needed
        if not cookie_get("force_mobile") and cookie_get('force_web') and c.subformat=='mobile': # If user is forcing m. then remove the force_web cookie
            log.debug('removing force_web cookie')
            cookie_delete('force_web')
        if c.format=='html' and c.subformat=='web' and request.environ.get('is_mobile') and not cookie_get('force_web') and request.environ['REQUEST_METHOD']=='GET':
            mobile_url = url('current', sub_domain='m', **request.GET)
            log.debug('redirecting mobile user to %s' % mobile_url)
            redirect(mobile_url)
        
        
        # Widget default settings ----------------------------------------------
        widget_theme = request.params.get(config['setting.widget.var_prefix']+'theme')
        if widget_theme not in widget_defaults:
            widget_theme = config['setting.widget.default_theme']
        c.widget = dict(widget_defaults[widget_theme])
        if get_subdomain_format() == 'widget':
            setup_widget_env()
        c.widget['theme'] = widget_theme # Set the widget theme to the one requested (this is needed because theme 'light' could be set, it does not exist so gets 'basic', then overwrites theme with 'light' again from set_env)

        # Log out if missing logged_in -------------------------------
        # The cache is active if logged_in is false. If the cookie is
        # missing (deleted, expired, something else) but the main session cookie
        # is still there then caching could activate by accident. As such, if
        # the logged_in cookie is missing, force a logout.
        if session_get('logged_in_user') and not request.cookies.get("logged_in"):
            log.warning("logged_in_user is set, but logged_in is missing")
            session.invalidate()


        # Login ----------------------------------------------------------------
        # Fetch logged in user from session id (if present)
        login_session_fields = ['logged_in_user', 'logged_in_persona', 'logged_in_persona_path', 'logged_in_persona_role']
        logged_in = {}
        for field in login_session_fields:
            logged_in[field] = session_get(field)
            setattr(c, field, logged_in[field])
        
        c.logged_in_user         = _get_member(logged_in['logged_in_user'])
        c.logged_in_persona      = c.logged_in_user
        if c.logged_in_user and not c.logged_in_persona_role:
            c.logged_in_persona_role = 'admin'
        if logged_in['logged_in_user'] != logged_in['logged_in_persona']:
            group_persona = _get_group(logged_in['logged_in_persona'])
            if group_persona: # and group_persona.id == c.logged_in_persona_path[-1]: #Wanted to double check group permissions matched the group being set
                role = get_lowest_role_for_user()
                if role:
                    c.logged_in_persona      = group_persona
                    c.logged_in_persona_role = role
        
        # Set Env - In the event of a server error these will be visable
        for field in login_session_fields:
            request.environ[field] = str(getattr(c, field))
            #print request.environ[field]
        
        if c.logged_in_user:
            request.environ['logged_in_user_email'] = c.logged_in_user.email_normalized
        
        # Setup Langauge -------------------------------------------------------
        #  - there is a way of setting fallback langauges, investigate?
        if 'lang' in request.params:
            _lang = request.params['lang'] # If lang set in URL
            session_set('lang', request.params['lang'])
        elif session_get('lang'):
            _lang = session_get('lang') # Lang set for this users session
        #elif c.logged_in_persona has lang:
        #    self._set_lang(c.logged_in_persona.?)     # Lang in user preferences
        #elif request.environ.get("Accept-Language"):
        #   langs = request.environ.get("Accept-Language").split(";")[0]
        #   for lang in langs:
        #       ...
        else:
            _lang = config['lang'] # Default lang in config file

        try:
            set_lang(_lang)
            formencode.api.set_stdtranslation(domain="civicboom", languages=[_lang])
            c.lang = _lang # only do this if the above succeeded
        except Exception:  # LanguageError
            pass
    
        
        # User pending regisration? --------------------------------------------
        # redirect to complete registration process
        if c.logged_in_user and c.logged_in_user.status == 'pending' and deny_pending_user(url('current')):
            set_flash_message(_('Please complete the registration process'))
            try:
                redirect(url(controller='register', action='new_user', id=c.logged_in_user.id))
            except RedirectException as e:
                abort(403, detail='user_registration_incomplete')


        # Session Flash Message ------------------------------------------------
        flash_message_session = session_remove('flash_message')
        if flash_message_session:
            try:
                overlay_status_message(c.result, json.loads(flash_message_session))
            except ValueError:
                overlay_status_message(c.result,            flash_message_session )
Example #30
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        request_start_memory_usage = get_mem_usage()
        if 'HTTP_X_FORWARDED_SCHEME' in environ:
            environ['wsgi.url_scheme'] = environ.pop('HTTP_X_FORWARDED_SCHEME')

        # Global variables
        # XXX reduce the scope of most of them
        c.breadcrumbs = None
        c.object_location = None
        c.hash = None
        c.email = None
        c.serve_file = None
        c.security_context = None
        c.obj_type = None
        c.results = None
        c.step = None
        c.searched = None
        c.slideshow = None
        c.structure = None
        c.login_form_url = None
        c.final_msg = None
        c.message_class = None
        c.text = None
        c.tags = None
        c.theme = None
        c.pylons_config = config

        c.testing = asbool(config.get('testing', False))
        c.mailing_list_host = config.get('mailing_list_host', '')
        c.google_tracker = config.get('google_tracker', '')
        c.facebook_app_id = config.get('facebook.appid')
        config.get('facebook.appid')
        c.redirect_to = request.params.get('redirect_to', '')
        c.came_from = request.params.get('came_from', '')
        c.came_from_search = False #if the user came from google search

        lang = session.get('language', None)
        if not lang:
            lang = get_country_code() or 'en'
            if lang not in ['lt', 'pl', 'en']:
                lang = 'en'
        session['language'] = lang
        session.save()
        set_lang(lang)
        c.lang = lang
        # XXX get these from db
        c.timezone = 'UTC'
        c.locale = 'en'

        succeeded = False
        try:
            # Record the time the user was last seen.
            c.user = current_user()
            if c.user is not None:
                environ['repoze.who.identity'] = c.user.id
                from ututi.model import User
                meta.Session.query(User).filter_by(id=c.user.id).with_lockmode('update').one()
                c.user.last_seen = datetime.utcnow()
                meta.Session.commit()
                user_email = c.user.email.email
            else:
                #the user is anonymous - check if he is coming from google search
                referrer = request.headers.get('referer', '')
                r = re.compile('www\.google\.[a-zA-Z]{2,4}/[url|search]')
                if r.search(referrer) is not None:
                    response.set_cookie('camefromsearch', 'yes', max_age=3600)
                    c.came_from_search = True
                else:
                    c.came_from_search = request.cookies.get('camefromsearch', None) == 'yes'
                user_email = 'ANONYMOUS'

            from ututi.model import Notification
            #find notification for the user
            c.user_notification = None
            if c.user is not None:
                  c.user_notification = Notification.unseen_user_notification(c.user)
            succeeded = True
        finally:
            if not succeeded:
                meta.Session.remove()

        if c.user is not None:
            c.theme = c.user.location.get_theme()

        self._push_custom_urls()

        request_start_walltime = time.time()
        request_start_cputime = time.clock()

        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            meta.Session.remove()
            self._pop_custom_urls()

            # Performance logging.
            perflog.log(logging.INFO,
                'request\t%(controller)s.%(action)s\t%(duration).4f\t%(duration_cpu).4f\t%(memory_usage)d\t%(user_email)s'
                 % dict(controller=environ['pylons.routes_dict'].get('controller'),
                        action=environ['pylons.routes_dict'].get('action'),
                        duration=time.time() - request_start_walltime,
                        duration_cpu=time.clock() - request_start_cputime,
                        memory_usage=get_mem_usage() - request_start_memory_usage,
                        user_email=user_email))