Example #1
0
 def get_day(self):
     if translation.get_language() == 'sr-latn':
         return self.day.day_sr
     if translation.get_language() == 'hu':
         return self.day.day_hu
     if translation.get_language() == 'en':
         return self.day.day_en
    def test_rule3(self):
        """
        Basic CharField/TextField test.
        Could as well call _test_field, just kept for reference.
        """
        title1_de = "title de"
        title1_en = "title en"
        n = TestModel.objects.create(title_de=title1_de, title_en=title1_en)
        self.failUnlessEqual(get_language(), "de")
        self.failUnlessEqual(n.title, title1_de)
        self.failUnlessEqual(n.title_de, title1_de)
        self.failUnlessEqual(n.title_en, title1_en)

        n.title_de = "Neuer Titel"
        n.save()
        self.failUnlessEqual(n.title, n.title_de)

        # Now switch to "en"
        trans_real.activate("en")
        self.failUnlessEqual(get_language(), "en")
        n.title_en = "New title"
        # the n.title field is not updated before the instance is saved
        n.save()
        self.failUnlessEqual(n.title, n.title_en)
        trans_real.deactivate()
    def test_rule2(self):
        """
        Basic CharField/TextField test.
        Could as well call _test_field, just kept for reference.
        """
        self.failUnlessEqual(get_language(), "de")
        title1_de = "title de"
        title1_en = "title en"
        n = TestModel.objects.create(title_de=title1_de, title_en=title1_en)
        self.failUnlessEqual(n.title, title1_de)
        self.failUnlessEqual(n.title_de, title1_de)
        self.failUnlessEqual(n.title_en, title1_en)

        title2 = "Neuer Titel"
        n.title = title2
        n.save()
        self.failUnlessEqual(n.title, title2)
        self.failUnlessEqual(n.title, n.title_de)

        trans_real.activate("en")
        self.failUnlessEqual(get_language(), "en")
        title3 = "new title"

        n.title = title3
        n.title_de = title1_de
        n.save()
        self.failUnlessEqual(n.title, title3)
        self.failUnlessEqual(n.title, n.title_en)
        self.failUnlessEqual(title1_de, n.title_de)

        trans_real.deactivate()
Example #4
0
 def get_meeting_type(self):
     if translation.get_language() == 'sr-latn':
         return u'%s' % (self.meeting_type.meeting_name_sr, )
     if translation.get_language() == 'hu':
         return u'%s' % (self.meeting_type.meeting_name_hu, )
     if translation.get_language() == 'en':
         return u'%s' % (self.meeting_type.meeting_name_en, )
    def _test_field(self, field_name, value1_de, value1_en, value2, value3,
                    deactivate=True):
        field_name_de = '%s_de' % field_name
        field_name_en = '%s_en' % field_name
        params = {'title_de': 'title de',
                  'title_en': 'title en'}
        params[field_name_de] = value1_de
        params[field_name_en] = value1_en

        n = TestModel.objects.create(**params)

        self.failUnlessEqual(get_language(), "de")
        self.failUnlessEqual(getattr(n, field_name), value1_de)
        self.failUnlessEqual(getattr(n, field_name_de), value1_de)
        self.failUnlessEqual(getattr(n, field_name_en), value1_en)

        setattr(n, field_name, value2)
        n.save()
        self.failUnlessEqual(getattr(n, field_name), getattr(n, field_name_de))

        # Now switch to "en"
        trans_real.activate("en")
        self.failUnlessEqual(get_language(), "en")
        setattr(n, field_name_en, value3)
        # the n.title field is not updated before the instance is saved
        n.save()
        self.failUnlessEqual(getattr(n, field_name), getattr(n, field_name_en))

        if deactivate:
            trans_real.deactivate()
    def _test_field(self, field_name, value_de, value_en, deactivate=True):
        field_name_de = '%s_de' % field_name
        field_name_en = '%s_en' % field_name
        params = {'title_de': 'title de',
                  'title_en': 'title en'}
        params[field_name_de] = value_de
        params[field_name_en] = value_en

        n = TestModel.objects.create(**params)
        # Language is set to "de" at this point
        self.failUnlessEqual(get_language(), "de")
        self.failUnlessEqual(getattr(n, field_name), value_de)
        self.failUnlessEqual(getattr(n, field_name_de), value_de)
        self.failUnlessEqual(getattr(n, field_name_en), value_en)
        # Now switch to "en"
        trans_real.activate("en")
        self.failUnlessEqual(get_language(), "en")
        # Should now be return the english one (just by switching the language)
        self.failUnlessEqual(getattr(n, field_name), value_en)

        n = TestModel.objects.create(**params)
        n.save()
        # Language is set to "en" at this point
        self.failUnlessEqual(getattr(n, field_name), value_en)
        self.failUnlessEqual(getattr(n, field_name_de), value_de)
        self.failUnlessEqual(getattr(n, field_name_en), value_en)
        trans_real.activate("de")
        self.failUnlessEqual(get_language(), "de")
        self.failUnlessEqual(getattr(n, field_name), value_de)

        if deactivate:
            trans_real.deactivate()
    def _test_field(self, field_name, value1_de, value1_en, value2, value3,
                    deactivate=True):
        field_name_de = '%s_de' % field_name
        field_name_en = '%s_en' % field_name
        params = {'title_de': 'title de',
                  'title_en': 'title en'}
        params[field_name_de] = value1_de
        params[field_name_en] = value1_en

        self.failUnlessEqual(get_language(), "de")
        n = TestModel.objects.create(**params)
        self.failUnlessEqual(getattr(n, field_name), value1_de)
        self.failUnlessEqual(getattr(n, field_name_de), value1_de)
        self.failUnlessEqual(getattr(n, field_name_en), value1_en)

        setattr(n, field_name, value2)
        n.save()
        self.failUnlessEqual(getattr(n, field_name), value2)
        self.failUnlessEqual(getattr(n, field_name), getattr(n, field_name_de))

        trans_real.activate("en")
        self.failUnlessEqual(get_language(), "en")

        setattr(n, field_name, value3)
        setattr(n, field_name_de, value1_de)
        n.save()
        self.failUnlessEqual(getattr(n, field_name), value3)
        self.failUnlessEqual(getattr(n, field_name), getattr(n, field_name_en))
        self.failUnlessEqual(value1_de, getattr(n, field_name_de))

        if deactivate:
            trans_real.deactivate()
Example #8
0
def i18n(request):
    return {
        'LANGUAGES': settings.LANGUAGES,
        'LANG': (settings.LANGUAGE_URL_MAP.get(translation.get_language())
                 or translation.get_language()),
        'DIR': 'rtl' if translation.get_language_bidi() else 'ltr',
    }
Example #9
0
    def get_template_sources(self, template_name, template_dirs=None):
        """
        Returns the absolute paths to "template_name", when appended to each
        directory in "template_dirs". Any paths that don't lie inside one of the
        template dirs are excluded from the result set, for security reasons.
        
        If current language is not default, prepend each path with language
        name. E.g. 'include/banner.html' would become 'de/include/banner.html'
        """
        if not template_dirs:
            template_dirs = settings.TEMPLATE_DIRS
        if get_language() != settings.LANGUAGE_CODE:
            lang = get_language()
            new_dirs = []
            for i in template_dirs:
                new_dirs.extend([safe_join(i, lang), i])
            template_dirs = new_dirs

        for template_dir in template_dirs:
            try:
                yield safe_join(template_dir, template_name)
            except UnicodeDecodeError:
                # The template dir name was a bytestring that wasn't valid UTF-8.
                raise
            except ValueError:
                # The joined path was located outside of this particular
                # template_dir (it might be inside another one, so this isn't
                # fatal).
                pass
Example #10
0
    def test_activate_locale(self):
        eq_(translation.get_language(), 'en-us')
        with UserProfile(username='******').activate_lang():
            eq_(translation.get_language(), 'en-us')

        with UserProfile(username='******', lang='fr').activate_lang():
            eq_(translation.get_language(), 'fr')
Example #11
0
def translate_commit_desc(value):
    """Translate commit description."""
    if value.startswith('Reverted repo'):
        # Change 'repo' to 'library' in revert commit msg, since 'repo' is
        # only used inside of seafile system.
        value = value.replace('repo', 'library')
        
    # Do nothing if current language is English.
    if translation.get_language() == 'en':
        return value
    
    if value.startswith('Reverted library'):
        return value.replace('Reverted library to status at', _('Reverted library to status at'))
    elif value.startswith('Reverted file'):
        def repl(matchobj):
            return _('Reverted file "%(file)s" to status at %(time)s.') % \
                {'file':matchobj.group(1), 'time':matchobj.group(2)}
        return re.sub('Reverted file "(.*)" to status at (.*)', repl, value)
    elif value.startswith('Recovered deleted directory'):
        return value.replace('Recovered deleted directory', _('Recovered deleted directory'))
    elif value.startswith('Changed library'):
        return value.replace('Changed library name or description', _('Changed library name or description'))
    elif value.startswith('Merged') or value.startswith('Auto merge'):
        return _('Auto merge by seafile system')
    else:
        # Use regular expression to translate commit description.
        # Commit description has two forms, e.g., 'Added "foo.txt" and 3 more files.' or 'Added "foo.txt".'
        operations = '|'.join(COMMIT_MSG_TRANSLATION_MAP.keys())
        patt = r'(%s) "(.*)"\s?(and ([0-9]+) more (files|directories))?' % operations

        ret_list = []
        for e in value.split('\n'):
            if not e:
                continue

            m = re.match(patt, e)
            if not m:
                ret_list.append(e)
                continue
        
            op = m.group(1)     # e.g., "Added"
            op_trans = _(op)
            file_name = m.group(2) # e.g., "foo.txt"
            has_more = m.group(3)  # e.g., "and 3 more files"
            n_files = m.group(4)   # e.g., "3"
            more_type = m.group(5) # e.g., "files"
    
            if has_more:
                if translation.get_language() == 'zh-cn':
                    typ = u'文件' if more_type == 'files' else u'目录'
                    ret = op_trans + u' "' + file_name + u'"以及另外' + n_files + u'个' + typ + '.'
                # elif translation.get_language() == 'ru':
                #     ret = ...
                else:
                    ret = e
            else:
                ret = op_trans + u' "' + file_name + u'".'
            ret_list.append(ret)

        return '\n'.join(ret_list)
Example #12
0
    def save(self, commit=True):
        ''' Saves the model
            If will always use the language specified in self.cleaned_data, with
            the usual None meaning 'call get_language()'. If instance has
            another language loaded, it gets reloaded with the new language.

            If no language is specified in self.cleaned_data, assume the instance
            is preloaded with correct language.
        '''
        assert self.is_valid(), ('Method save() must not be called on an invalid '
                                 'form. Check the result of .is_valid() before '
                                 'calling save().')

        # Get the right translation for object and language
        # It should have been done in _post_clean, but instance may have been
        # changed since.
        enforce = 'language_code' in self.cleaned_data
        if getattr(self, 'is_edit', False):
            language = self.language or get_language()
        else:
            language = self.cleaned_data.get('language_code') or get_language()
        translation = load_translation(self.instance, language, enforce)

        # Fill the translated fields with values from the form
        excludes = list(self._meta.exclude) + ['master', 'language_code']
        translation = construct_instance(self, translation,
                                         self._meta.fields, excludes)
        if getattr(self, 'is_edit', False):
            translation.language_code = \
                self.cleaned_data.get('language_code', None) or self.new_lang
        set_cached_translation(self.instance, translation)

        # Delegate shared fields to super()
        return super(BaseTranslatableModelForm, self).save(commit=commit)
Example #13
0
def preferences(request):
  if request.method == 'POST':
    form = PreferencesForm(request.POST)
    if form.is_valid():
      try:
        newdata = form.cleaned_data
        request.user.language = newdata['language']
        request.user.theme = newdata['theme']
        request.user.pagesize = newdata['pagesize']
        request.user.save()
        # Switch to the new theme and language immediately
        request.theme = newdata['theme']
        if newdata['language'] == 'auto':
          newdata['language'] = translation.get_language_from_request(request)
        if translation.get_language() != newdata['language']:
          translation.activate(newdata['language'])
          request.LANGUAGE_CODE = translation.get_language()
        messages.add_message(request, messages.INFO, force_unicode(_('Successfully updated preferences')))
      except Exception as e:
        logger.error("Failure updating preferences: %s" % e)
        messages.add_message(request, messages.ERROR, force_unicode(_('Failure updating preferences')))
  else:
    pref = request.user
    form = PreferencesForm({
      'language': pref.language,
      'theme': pref.theme,
      'pagesize': pref.pagesize,
      })
  return render_to_response('common/preferences.html', {
     'title': _('Edit my preferences'),
     'form': form,
     },
     context_instance=RequestContext(request))
Example #14
0
def _get_placeholder(current_page, page, context, name):
    placeholder_cache = getattr(current_page, '_tmp_placeholders_cache', {})
    if page.pk in placeholder_cache:
        placeholder = placeholder_cache[page.pk].get(name, None)
        if placeholder:
            return placeholder
    placeholder_cache[page.pk] = {}
    placeholders = page.rescan_placeholders().values()
    fetch_placeholders = []
    request = context['request']
    if not get_cms_setting('PLACEHOLDER_CACHE') or (hasattr(request, 'toolbar') and request.toolbar.edit_mode):
        fetch_placeholders = placeholders
    else:
        for placeholder in placeholders:
            cached_value = get_placeholder_cache(placeholder, get_language())
            if cached_value is not None:
                restore_sekizai_context(context, cached_value['sekizai'])
                placeholder.content_cache = cached_value['content']
            else:
                fetch_placeholders.append(placeholder)
            placeholder.cache_checked = True
    if fetch_placeholders:
        assign_plugins(context['request'], fetch_placeholders, page.get_template(),  get_language())
    for placeholder in placeholders:
        placeholder_cache[page.pk][placeholder.slot] = placeholder
        placeholder.page = page
    current_page._tmp_placeholders_cache = placeholder_cache
    placeholder = placeholder_cache[page.pk].get(name, None)
    if page.application_urls and not placeholder:
        raise PlaceholderNotFound(
            '"%s" placeholder not found in an apphook application. Please use a static placeholder instead.' % name)
    return placeholder
Example #15
0
def traverse_object(request, path):
    """Returns the the object with the given path.
    """
    language = translation.get_language()

    # CACHE
    cache_key = "%s-traverse-obj-%s-%s-%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX,
                                              path, request.user.id, language)
    obj = cache.get(cache_key)
    if obj:
        return obj

    paths = path.split("/")
    language = translation.get_language()

    try:
        obj = lfc.utils.get_content_object(request, slug=paths[0],
            parent=None, language__in = ("0", language))
    except lfc.models.BaseContent.DoesNotExist:
        raise Http404

    for path in paths[1:]:
        try:
            obj = obj.children.get(slug=path, language__in = ("0", obj.language)).get_content_object()
        except lfc.models.BaseContent.DoesNotExist:
            raise Http404

    cache.set(cache_key, obj)
    return obj
Example #16
0
def get_format_modules(reverse=False):
    """
    Returns an iterator over the format modules found in the project and Django
    """
    modules = []
    if not check_for_language(get_language()) or not settings.USE_L10N:
        return modules
    locale = to_locale(get_language())
    if settings.FORMAT_MODULE_PATH:
        format_locations = [settings.FORMAT_MODULE_PATH + '.%s']
    else:
        format_locations = []
    format_locations.append('django.conf.locale.%s')
    for location in format_locations:
        for l in (locale, locale.split('_')[0]):
            try:
                mod = import_module('.formats', location % l)
            except ImportError:
                pass
            else:
                # Don't return duplicates
                if mod not in modules:
                    modules.append(mod)
    if reverse:
        modules.reverse()
    return modules
Example #17
0
    def test_activate_locale(self):
        assert translation.get_language() == 'en-us'
        with UserProfile(username='******').activate_lang():
            assert translation.get_language() == 'en-us'

        with UserProfile(username='******', lang='fr').activate_lang():
            assert translation.get_language() == 'fr'
Example #18
0
def when_text(d,t=None):
    """
    Return a string with a concise representation of the given 
    date and time combination.
    Examples:
    
    >>> when_text(datetime.date(2013,12,25))
    u'2013 Dec 25 (Wed)'
    
    >>> when_text(datetime.date(2013,12,25),datetime.time(17,15,00))
    u'2013 Dec 25 (Wed) 17:15'
    
    >>> when_text(None)
    u''
    
    """
    if d is None: return ''
    fmt = 'yyyy MMM dd (EE)'
    if t is None: 
        return format_date(d,fmt,locale=to_locale(translation.get_language()))
    #~ if d.year == datetime.date.today().year:
        #~ fmt = "%a" + settings.SITE.time_format_strftime
    #~ else:
        #~ fmt = "%a %y %b %d" + settings.SITE.time_format_strftime
    #~ fmt = "%a %Y %b %d " + settings.SITE.time_format_strftime
    #~ return datetime.datetime.combine(d,t).strftime(fmt)
    fmt += " HH:mm"
    return format_datetime(datetime.datetime.combine(d,t),fmt,locale=to_locale(translation.get_language()))
Example #19
0
def get_best_locale(request, locale):
    """
    Returns the most appropriate locale from the list of supported locales.
    This can either be the locale itself (if it's supported), the main locale
    for that language if any or failing any of that the default `en-US`.

    Adapted from `activate_locale` in https://github.com/mozilla/affiliates/blob/master/apps/facebook/utils.py
    """
    # HACK: It's not totally clear to me where Django or tower do the matching
    # that equates locales like es-LA to es, and I'm scared enough of getting it
    # wrong to want to avoid it for the first release. So instead, we'll
    # activate the requested locale, and then check what locale got chosen by
    # django as the usable locale, and match that against our locale whitelist.
    # TODO: Properly filter out locales prior to calling activate.
    old_locale = get_language()
    tower.activate(locale)
    lang = get_language()

    if lang not in settings.FACEBOOK_LOCALES:
        lang_prefix = lang.split('-')[0]
        tower.activate(lang_prefix)
        lang = get_language()

        if lang not in settings.FACEBOOK_LOCALES:
            try:
                lang = next(locale for locale in settings.FACEBOOK_LOCALES
                    if locale.startswith(lang_prefix))
            except TypeError:
                lang = 'en-US'

    tower.activate(old_locale)
    return lang
Example #20
0
def edit_item(request, item_id):
    if not request.user.is_staff:
        raise Http403

    item = Item.objects.get(pk=item_id)
    revision = item.get_latest(lang=get_language())

    if request.method == "POST":
        form = NewRevisionForm(request.POST, instance=revision)
        args = {"form": form, "item": item}
        if form.is_valid():
            # We want to save a new one
            form.instance.id = None
            # For now just assume that missing revision == missing content
            if revision is None:
                content = Content(item=item, language=get_language())
                content.save()
                revision = form.save(commit=False)
                revision.content = content
                revision.save()
            else:
                form.save()
            # First iteration, at least news are shown on main page
            return redirect("/")
    else:
        form = NewRevisionForm(instance=revision)
        args = {"revision": revision, "item": item, "form": form}

    return render_to_response("edit_item.html", args, context_instance=RequestContext(request))
    def get_description(self):
        """
        Returns the first available text from either the excerpt or
        content placeholder.

        """
        content = ''
        for plugin in self.excerpt.get_plugins():
            try:
                if plugin.text.language == get_language():
                    content = plugin.text.body
            except:
                pass
            if content:
                break
        if not content:
            for plugin in self.content.get_plugins():
                try:
                    if plugin.text.language == get_language():
                        content = plugin.text.body
                except:
                    pass
                if content:
                    break

        # remove html tags and escape the rest
        pattern = re.compile('<.*?>')
        content = pattern.sub('', content)
        text = escape(content)
        return text
Example #22
0
    def to_python(self, value):
        if isinstance(value, TransDbValue):
            return value

        if isinstance(value, dict): # formfield method makes this function be called with value as a dict
            python_value = value
        else:
            try:
                python_value = eval(value)
                for k,v in python_value.items():
                    python_value[k] = smart_unicode(v)
            except Exception:
                python_value = None
        if isinstance(python_value, dict):
            if python_value.has_key(get_language()) and python_value[get_language()]:
                result = TransDbValue(python_value[get_language()])
            elif python_value.has_key(settings.LANGUAGE_CODE) and python_value[settings.LANGUAGE_CODE]:
                result = TransDbValue(python_value[settings.LANGUAGE_CODE])
            else:
                val = "bal"
                for item in python_value.items():
                    try:
                        val = item[1]
                    except:
                        pass
                    if val: break

                result = TransDbValue(python_value.items()[0][1])
            result.raw_data = python_value
        else:
            result = TransDbValue(value)
            result.raw_data = {settings.LANGUAGE_CODE: value}
        return result
Example #23
0
 def __unicode__(self):
     if translation.get_language() == 'sr-latn':
         return self.title_sr
     elif translation.get_language() == 'hu':
         return self.title_hu
     elif translation.get_language() == 'en':
         return self.title_en
Example #24
0
    def test_message_catalog_translations(self):
        """
        Test: Message catalog from FakeTranslation should return required translations.
        """
        _translator = FakeTranslations.translator(
            {
                'es': {'Hello': 'es-hello-world'},
                'fr': {'Hello': 'fr-hello-world'},
            },
        )
        localedir = '/translations'
        translation.activate("es")
        with mock.patch('gettext.translation', return_value=_translator(domain='text', localedir=localedir,
                                                                        languages=[get_language()])):
            i18n_service = self.get_module_i18n_service(self.descriptor)
            self.assertEqual(i18n_service.ugettext('Hello'), 'es-hello-world')

        translation.activate("ar")
        with mock.patch('gettext.translation', return_value=_translator(domain='text', localedir=localedir,
                                                                        languages=[get_language()])):
            i18n_service = self.get_module_i18n_service(self.descriptor)
            self.assertEqual(i18n_service.ugettext('Hello'), 'Hello')
            self.assertNotEqual(i18n_service.ugettext('Hello'), 'fr-hello-world')
            self.assertNotEqual(i18n_service.ugettext('Hello'), 'es-hello-world')

        translation.activate("fr")
        with mock.patch('gettext.translation', return_value=_translator(domain='text', localedir=localedir,
                                                                        languages=[get_language()])):
            i18n_service = self.get_module_i18n_service(self.descriptor)
            self.assertEqual(i18n_service.ugettext('Hello'), 'fr-hello-world')
Example #25
0
def test_applied_attributes():
    product = get_default_product()
    for spec in ATTR_SPECS:  # This loop sets each attribute twice. That's okay.
        attr = Attribute.objects.get(identifier=spec["identifier"])
        pa, _ = ProductAttribute.objects.get_or_create(product=product, attribute=attr)
        _populate_applied_attribute(pa)
        pa.save()
        if not attr.is_translated:
            product.set_attribute_value(attr.identifier, pa.value)

    assert product.get_attribute_value("bogomips") == 320, "integer attribute loaded neatly"
    product.set_attribute_value("bogomips", 480)
    assert product.get_attribute_value("bogomips") == 480, "integer attribute updated neatly"
    Product.cache_attributes_for_targets(
        applied_attr_cls=ProductAttribute,
        targets=[product],
        attribute_identifiers=[a["identifier"] for a in ATTR_SPECS],
        language=get_language()
    )
    assert (get_language(), "bogomips",) in product._attr_cache, "integer attribute in cache"
    assert product.get_attribute_value("bogomips") == 480, "integer attribute value in cache"
    assert product.get_attribute_value("ba:gelmips", default="Britta") == "Britta", "non-existent attributes return default value"
    assert product._attr_cache[(get_language(), "ba:gelmips")] is NoSuchAttributeHere, "cache miss saved"
    attr_info = product.get_all_attribute_info(language=get_language(), visibility_mode=AttributeVisibility.SHOW_ON_PRODUCT_PAGE)
    assert set(attr_info.keys()) <= set(a["identifier"] for a in ATTR_SPECS), "get_all_attribute_info gets all attribute info"
Example #26
0
 def test_rule2(self):                                            
     """
     Rule 2: Assigning a value to the original field also updates the value
     in the associated translation field of the default language
     """
     self.failUnlessEqual(get_language(), "de")
     title1_de = "title de"
     title1_en = "title en"
     n = TestModel.objects.create(title_de=title1_de, title_en=title1_en)                            
     self.failUnlessEqual(n.title, title1_de)
     self.failUnlessEqual(n.title_de, title1_de)
     self.failUnlessEqual(n.title_en, title1_en)
                 
     title2 =  "Neuer Titel"                   
     n.title = title2
     n.save()
     self.failUnlessEqual(n.title, title2)
     self.failUnlessEqual(n.title, n.title_de)
     
     trans_real.activate("en")
     self.failUnlessEqual(get_language(), "en")
     title3 = "new title"
     
     n.title = title3
     n.title_de = title1_de
     n.save()
     self.failUnlessEqual(n.title, title3)
     self.failUnlessEqual(n.title, n.title_en)
     self.failUnlessEqual(title1_de, n.title_de)
     
     trans_real.deactivate()                
Example #27
0
 def test_rule3(self):
     """
     Rule 3: Assigning a value to a translation field of the default language
     also updates the original field - note that the value of the original 
     field will not be updated until the model instance is saved.
     """
     title1_de = "title de"
     title1_en = "title en"
     n = TestModel.objects.create(title_de=title1_de, title_en=title1_en)                            
     self.failUnlessEqual(get_language(), "de")
     self.failUnlessEqual(n.title, title1_de)
     self.failUnlessEqual(n.title_de, title1_de)
     self.failUnlessEqual(n.title_en, title1_en)
                 
     n.title_de = "Neuer Titel"
     n.save()
     self.failUnlessEqual(n.title, n.title_de)
     
     # Now switch to "en"
     trans_real.activate("en")
     self.failUnlessEqual(get_language(), "en")
     n.title_en = "New title"
     # the n.title field is not updated before the instance is saved
     n.save()
     self.failUnlessEqual(n.title, n.title_en)
     trans_real.deactivate()
Example #28
0
def login(request,
          template_name='registration/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=LoginForm):
    '''
    Displays the login form and handles the login action.
    When the User is logged on, we'll try to read the language from his/her
    profile and update the current language accordingly.
    '''
    if django.VERSION < (1, 2):
        response = auth_views.login(request, template_name=template_name, redirect_field_name=redirect_field_name)
    else:
        response = auth_views.login(request, template_name=template_name, redirect_field_name=redirect_field_name, authentication_form=authentication_form)

    if request.method == 'POST':
        try:
            p = request.user.get_profile()
        except AttributeError:
            lang_code = translation.get_language()
        except ObjectDoesNotExist:
            lang_code = translation.get_language()
        else:
            lang_code = p.language

            if lang_code == '':
                lang_code = translation.get_language()
                p.language = lang_code
                p.save()
        set_language_on_response(request, response, lang_code)

    return response
Example #29
0
 def __unicode__(self):
     if translation.get_language() == 'sr-latn':
         return self.intro_sr
     if translation.get_language() == 'hu':
         return self.intro_hu
     if translation.get_language() == 'en':
         return self.intro_en
Example #30
0
def language_chooser(context, template=NOT_PROVIDED, i18n_mode="raw"):
    """
    Displays a language chooser
    - template: template used to render the language chooser
    """
    if template in MARKERS:
        i18n_mode = template
        template = NOT_PROVIDED
    if template is NOT_PROVIDED:
        template = "menu/language_chooser.html"
    if not i18n_mode in MARKERS:
        i18n_mode = "raw"
    try:
        # If there's an exception (500), default context_processors may not be called.
        request = context["request"]
    except KeyError:
        return {"template": "cms/content.html"}
    marker = MARKERS[i18n_mode]
    cms_languages = dict(settings.CMS_LANGUAGES)
    current_lang = get_language()
    site = Site.objects.get_current()
    cache_key = "%s-language-chooser-%s-%s-%s" % (settings.CMS_CACHE_PREFIX, site.pk, current_lang, i18n_mode)
    languages = cache.get(cache_key, [])
    if not languages:
        for lang in settings.CMS_FRONTEND_LANGUAGES:
            if lang in cms_languages:
                languages.append((lang, marker(cms_languages[lang], lang)))
        if current_lang != get_language():
            activate(current_lang)
        cache.set(cache_key, languages)
    lang = get_language_from_request(request, request.current_page)
    context.update({"languages": languages, "current_language": lang, "template": template})
    return context
Example #31
0
 def get_extra_restriction(self, where_class, alias, related_alias):
     return ColConstraint(alias, 'lang', get_language())
Example #32
0
class Video(models.Model):
    video = models.FileField(
        _('Video'),  upload_to=get_storage_path, max_length=255)
    allow_downloading = models.BooleanField(
        _('allow downloading'), default=False)
    is_360 = models.BooleanField(_('video 360'), default=False)
    title = models.CharField(_('Title'), max_length=250)
    slug = models.SlugField(_('Slug'), unique=True, max_length=255,
                            help_text=_(
                                'Used to access this instance, the "slug" is a short label containing only letters, numbers, underscore or dash top.'),
                            editable=False)
    owner = models.ForeignKey(User, verbose_name=_('Owner'))

    date_added = models.DateField(_('Date added'), default=datetime.now)
    date_evt = models.DateField(
        _(u'Date of event'), default=datetime.now, blank=True, null=True)

    cursus = models.CharField(
        _('University course'), max_length=1, choices=settings.CURSUS_CODES, default="0")

    main_lang = models.CharField(
        _('Main language'), max_length=2, choices=MAIN_LANG_CHOICES, default=get_language())

    description = RichTextField(
        _('Description'), config_name='complete', blank=True)

    view_count = models.PositiveIntegerField(
        _('View count'), default=0, editable=False)

    encoding_in_progress = models.BooleanField(
        _('Encoding in progress'), default=False, editable=False)
    encoding_status = models.CharField(
        _('Encoding status'), max_length=250, editable=False, blank=True, null=True)

    thumbnail = FilerImageField(
        null=True, blank=True, verbose_name=_('Thumbnail'))

    to_encode = models.BooleanField(default=False, editable=False)

    overview = models.ImageField(
        _('Overview'), null=True, upload_to=get_storage_path, blank=True, max_length=255, editable=False)

    duration = models.IntegerField(
        _('Duration'), default=0, editable=False, blank=True)
    infoVideo = models.TextField(null=True, blank=True, editable=False)

    class Meta:
        ordering = ['-date_added', '-id']
        get_latest_by = 'date_added'
        verbose_name = _("video")
        verbose_name_plural = _("videos")
        abstract = True

    def __unicode__(self):
        return u"Titre:%s - Prop:%s - Date:%s" % (self.title, self.owner, self.date_added)

    def __str__(self):
        return "%s" % (self.title)

    def filename(self):
        return os.path.basename(self.video.name)

    def admin_thumbnail(self):
        try:
            if self.thumbnail is None:
                return ""
            else:
                return "<img src=\"%s\" alt=\"%s\" />" % (self.thumbnail.icons['64'], self.title)
        except:
            return ""
    admin_thumbnail.short_description = _('Thumbnail')
    admin_thumbnail.allow_tags = True

    def duration_in_time(self):
        return time.strftime('%H:%M:%S', time.gmtime(self.duration))

    duration_in_time.short_description = _('Duration')
    duration_in_time.allow_tags = True
Example #33
0
def _get_locale_analyzer():
    analyzer = amo.SEARCH_LANGUAGE_TO_ANALYZER.get(translation.get_language())
    if not settings.ES_USE_PLUGINS and analyzer in amo.SEARCH_ANALYZER_PLUGINS:
        return None
    return analyzer
Example #34
0
    ('THANKS', 'Thanks'),
    ('SUPPORTER', 'Seisho student'),
    ('LOVER', 'Revue performer'),
    ('AMBASSADOR', 'Play stage manager'),
    ('PRODUCER', 'Revue producer'),
    ('DEVOTEE', 'Starlight reached'),
)

############################################################
# Activities

MINIMUM_LIKES_POPULAR = 5

ACTIVITY_TAGS = [
    # Revue Starlight
    ('revuestarlight', lambda: LICENSE_NAME_PER_LANGUAGE.get(get_language(), LICENSE_NAME)),
    ('stagegirls', _('Stage girls')),
    ('voiceactresses', _('Voice actresses')),
    ('anime', lambda: u'{} / {} / {} ({})'.format(
        _('Anime'),
        _('Manga'),
        _('Movie'),
        LICENSE_NAME_PER_LANGUAGE.get(get_language(), LICENSE_NAME),
    )),
    ('irlevent', lambda: u'{} / {} ({})'.format(
        _('Meetups'),
        _('Events'),
        LICENSE_NAME_PER_LANGUAGE.get(get_language(), LICENSE_NAME),
    )),

    # Relive
Example #35
0
 def inner(*args, **kwargs):
     prev_language = translation.get_language()
     if prev_language != settings.LANGUAGE_CODE:
         translation.activate(settings.LANGUAGE_CODE)
     return func(*args, **kwargs)
Example #36
0
from django.shortcuts import get_object_or_404, redirect, render
from django.utils import timezone
from django.utils.translation import get_language, ugettext as _
from django.views.decorators.cache import cache_page
from django.views.decorators.http import last_modified
from django.views.i18n import javascript_catalog
from shibboleth.views import ShibbolethLogoutView, LOGOUT_SESSION_KEY

from contrib.mcp.client import MCPClient
from main import models
from lxml import etree
from components import helpers
from archivematicaFunctions import escape


@cache_page(86400, key_prefix="js18n-%s" % get_language())
@last_modified(lambda req, **kw: timezone.now())
def cached_javascript_catalog(request, domain="djangojs", packages=None):
    return javascript_catalog(request, domain, packages)


""" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
      Home
    @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ """


def home(request):
    # clean up user's session-specific data
    if "user_temp_data_cleanup_ran" not in request.session:
        # create all transfer metadata sets created by user
        transfer_metadata_sets = models.TransferMetadataSet.objects.filter(
Example #37
0
 def get_extra_descriptor_filter(self):
     return {'lang': get_language()}
Example #38
0
 def post(self, request, *args, **kwargs):
     return self.do(self.request.event.id,
                    get_or_create_cart_id(self.request),
                    translation.get_language())
Example #39
0
def create_account_with_params(request, params):
    """
    Given a request and a dict of parameters (which may or may not have come
    from the request), create an account for the requesting user, including
    creating a comments service user object and sending an activation email.
    This also takes external/third-party auth into account, updates that as
    necessary, and authenticates the user for the request's session.

    Does not return anything.

    Raises AccountValidationError if an account with the username or email
    specified by params already exists, or ValidationError if any of the given
    parameters is invalid for any other reason.

    Issues with this code:
    * It is non-transactional except where explicitly wrapped in atomic to
      alleviate deadlocks and improve performance. This means failures at
      different places in registration can leave users in inconsistent
      states.
    * Third-party auth passwords are not verified. There is a comment that
      they are unused, but it would be helpful to have a sanity check that
      they are sane.
    * The user-facing text is rather unfriendly (e.g. "Username must be a
      minimum of two characters long" rather than "Please use a username of
      at least two characters").
    * Duplicate email raises a ValidationError (rather than the expected
      AccountValidationError). Duplicate username returns an inconsistent
      user message (i.e. "An account with the Public Username '{username}'
      already exists." rather than "It looks like {username} belongs to an
      existing account. Try again with a different username.") The two checks
      occur at different places in the code; as a result, registering with
      both a duplicate username and email raises only a ValidationError for
      email only.
    """
    # Copy params so we can modify it; we can't just do dict(params) because if
    # params is request.POST, that results in a dict containing lists of values
    params = dict(list(params.items()))

    # allow to define custom set of required/optional/hidden fields via configuration
    extra_fields = configuration_helpers.get_value(
        'REGISTRATION_EXTRA_FIELDS',
        getattr(settings, 'REGISTRATION_EXTRA_FIELDS', {})
    )
    if is_registration_api_v1(request):
        if 'confirm_email' in extra_fields:
            del extra_fields['confirm_email']

    # registration via third party (Google, Facebook) using mobile application
    # doesn't use social auth pipeline (no redirect uri(s) etc involved).
    # In this case all related info (required for account linking)
    # is sent in params.
    # `third_party_auth_credentials_in_api` essentially means 'request
    # is made from mobile application'
    third_party_auth_credentials_in_api = 'provider' in params
    is_third_party_auth_enabled = third_party_auth.is_enabled()

    if is_third_party_auth_enabled and (pipeline.running(request) or third_party_auth_credentials_in_api):
        params["password"] = generate_password()

    # in case user is registering via third party (Google, Facebook) and pipeline has expired, show appropriate
    # error message
    if is_third_party_auth_enabled and ('social_auth_provider' in params and not pipeline.running(request)):
        raise ValidationError(
            {'session_expired': [
                _(u"Registration using {provider} has timed out.").format(
                    provider=params.get('social_auth_provider'))
            ]}
        )

    extended_profile_fields = configuration_helpers.get_value('extended_profile_fields', [])
    # Can't have terms of service for certain SHIB users, like at Stanford
    registration_fields = getattr(settings, 'REGISTRATION_EXTRA_FIELDS', {})
    tos_required = (
        registration_fields.get('terms_of_service') != 'hidden' or
        registration_fields.get('honor_code') != 'hidden'
    )

    form = AccountCreationForm(
        data=params,
        extra_fields=extra_fields,
        extended_profile_fields=extended_profile_fields,
        do_third_party_auth=False,
        tos_required=tos_required,
    )
    custom_form = get_registration_extension_form(data=params)

    # Perform operations within a transaction that are critical to account creation
    with outer_atomic(read_committed=True):
        # first, create the account
        (user, profile, registration) = do_create_account(form, custom_form)

        third_party_provider, running_pipeline = _link_user_to_third_party_provider(
            is_third_party_auth_enabled, third_party_auth_credentials_in_api, user, request, params,
        )

        new_user = authenticate_new_user(request, user.username, form.cleaned_data['password'])
        django_login(request, new_user)
        request.session.set_expiry(0)

    # Sites using multiple languages need to record the language used during registration.
    # If not, compose_and_send_activation_email will be sent in site's default language only.
    create_or_set_user_attribute_created_on_site(user, request.site)
    preferences_api.set_user_preference(user, LANGUAGE_KEY, get_language())

    # Check if system is configured to skip activation email for the current user.
    skip_email = _skip_activation_email(
        user, running_pipeline, third_party_provider,
    )

    if skip_email:
        registration.activate()
    else:
        compose_and_send_activation_email(user, profile, registration)

    if settings.FEATURES.get('ENABLE_DISCUSSION_EMAIL_DIGEST'):
        try:
            enable_notifications(user)
        except Exception:  # pylint: disable=broad-except
            log.exception(u"Enable discussion notifications failed for user {id}.".format(id=user.id))

    _track_user_registration(user, profile, params, third_party_provider)

    # Announce registration
    REGISTER_USER.send(sender=None, user=user, registration=registration)

    create_comments_service_user(user)

    try:
        _record_registration_attributions(request, new_user)
    # Don't prevent a user from registering due to attribution errors.
    except Exception:   # pylint: disable=broad-except
        log.exception('Error while attributing cookies to user registration.')

    # TODO: there is no error checking here to see that the user actually logged in successfully,
    # and is not yet an active user.
    if new_user is not None:
        AUDIT_LOG.info(u"Login success on new account creation - {0}".format(new_user.username))

    return new_user
Example #40
0
 def get_language(self):
     """
     Define the language of the current view, defaults to the active language.
     """
     return translation.get_language()
Example #41
0
        def _data(self, request, cleaned, *args, explain=None, **kwargs):
            m_search = MultiSearch()
            search = Search(using=connection,
                            index=settings.ELASTICSEARCH_COMMON_ALIAS_NAME,
                            extra={'size': 0})
            search.aggs.bucket(
                'documents_by_type',
                TermsFacet(field='model').get_aggregation()).bucket(
                    'by_month',
                    DateHistogramFacet(field='created',
                                       interval='month',
                                       min_doc_count=0).get_aggregation())
            d_search = DatasetDocument().search().extra(size=0).filter(
                'match', status='published')
            r_search = ResourceDocument().search().extra(size=0).filter(
                'match', status='published')

            d_search.aggs.bucket(
                'datasets_by_institution',
                NestedFacet(
                    'institution',
                    TermsFacet(field='institution.id')).get_aggregation())

            d_search.aggs.bucket(
                'datasets_by_categories',
                NestedFacet(
                    'categories',
                    TermsFacet(field='categories.id', min_doc_count=1,
                               size=50)).get_aggregation())
            d_search.aggs.bucket(
                'datasets_by_category',
                NestedFacet(
                    'category',
                    TermsFacet(field='category.id', min_doc_count=1,
                               size=50)).get_aggregation())

            d_search.aggs.bucket('datasets_by_tag',
                                 TermsFacet(field='tags').get_aggregation())

            d_search.aggs.bucket(
                'datasets_by_keyword',
                Nested(aggs={
                    'inner':
                    Filter(
                        aggs={'inner': Terms(field='keywords.name')},
                        term={'keywords.language': get_language()},
                    )
                },
                       path='keywords'))

            d_search.aggs.bucket('datasets_by_formats',
                                 TermsFacet(field='formats').get_aggregation())
            d_search.aggs.bucket(
                'datasets_by_openness_scores',
                TermsFacet(field='openness_scores').get_aggregation())
            r_search.aggs.bucket('resources_by_type',
                                 TermsFacet(field='type').get_aggregation())
            m_search = m_search.add(search)
            m_search = m_search.add(d_search)
            m_search = m_search.add(r_search)
            if explain == '1':
                return m_search.to_dict()
            try:
                resp1, resp2, resp3 = m_search.execute()
                # TODO: how to concatenate two responses in more elegant way?
                resp1.aggregations.datasets_by_institution = resp2.aggregations.datasets_by_institution
                resp1.aggregations.datasets_by_categories = resp2.aggregations.datasets_by_categories
                resp1.aggregations.datasets_by_category = resp2.aggregations.datasets_by_category
                resp1.aggregations.datasets_by_tag = resp2.aggregations.datasets_by_tag
                resp1.aggregations.datasets_by_keyword = resp2.aggregations.datasets_by_keyword
                resp1.aggregations.datasets_by_formats = resp2.aggregations.datasets_by_formats
                resp1.aggregations.datasets_by_openness_scores = resp2.aggregations.datasets_by_openness_scores
                resp1.aggregations.resources_by_type = resp3.aggregations.resources_by_type
                return resp1
            except TransportError as err:
                try:
                    description = err.info['error']['reason']
                except KeyError:
                    description = err.error
                raise falcon.HTTPBadRequest(description=description)
Example #42
0
def get_current_cc(language=None):
    language = language or translation.get_language()
    return language.split('-')[-1].upper()
Example #43
0
def user_profile(request):
    profile = request.user.profile

    if not profile.language:
        profile.language = get_language()
        profile.save(update_fields=['language'])

    form_classes = [
        ProfileForm,
        SubscriptionForm,
        UserSettingsForm,
        DashboardSettingsForm,
        UserForm,
    ]
    forms = [form.from_request(request) for form in form_classes]
    forms.extend(get_notification_forms(request))
    all_backends = set(load_backends(social_django.utils.BACKENDS).keys())

    if request.method == 'POST':
        if all(form.is_valid() for form in forms):
            # Save changes
            for form in forms:
                form.save()

            # Change language
            set_lang(request, request.user.profile)

            # Redirect after saving (and possibly changing language)
            response = redirect_profile(request.POST.get('activetab'))

            # Set language cookie and activate new language (for message below)
            lang_code = profile.language
            response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
            translation.activate(lang_code)

            messages.success(request, _('Your profile has been updated.'))

            return response
    else:
        if not request.user.has_usable_password() and 'email' in all_backends:
            messages.warning(
                request, render_to_string('accounts/password-warning.html'))

    social = request.user.social_auth.all()
    social_names = [assoc.provider for assoc in social]
    new_backends = [
        x for x in all_backends if x == 'email' or x not in social_names
    ]
    license_projects = Component.objects.filter(
        project__in=request.user.allowed_projects).exclude(
            license='').order_project()

    result = render(
        request, 'accounts/profile.html', {
            'languagesform': forms[0],
            'subscriptionform': forms[1],
            'usersettingsform': forms[2],
            'dashboardsettingsform': forms[3],
            'userform': forms[4],
            'notification_forms': forms[5:],
            'all_forms': forms,
            'profile': profile,
            'title': _('User profile'),
            'licenses': license_projects,
            'associated': social,
            'new_backends': new_backends,
            'auditlog': request.user.auditlog_set.order()[:20],
        })
    result.set_cookie(settings.LANGUAGE_COOKIE_NAME, profile.language)
    return result
def common(request):
    context = {}
    context['paypal_return_url'] = settings.PAYPAL_RETURN_URL
    context['paypal_notify_url'] = settings.PAYPAL_NOTIFY_URL
    context['paypal_business_name'] = settings.PAYPAL_BUSINESS_NAME
    context['paypal_receiver_email'] = settings.PAYPAL_RECEIVER_EMAIL
    context['paypal_submit_url'] = settings.PAYPAL_SUBMIT_URL
    context['stripe_public_key'] = settings.STRIPE_PUBLIC_KEY
    context['stripe_secret_key'] = settings.STRIPE_SECRET_KEY

    context['ga_is_on'] = settings.GA_IS_ON
    context['latestblogs'] = BlogEntry.objects.filter(
        is_draft=False, title__isnull=False).exclude(
            title__exact="None").order_by('-date_added')[:3]
    context['static_url'] = settings.STATIC_URL
    context['thumb_large'] = settings.THUMB_LARGE
    context['thumb_home_large'] = settings.THUMB_HOME_LARGE
    context['thumb_medium'] = settings.THUMB_MEDIUM
    context['thumb_small'] = settings.THUMB_SMALL

    context['date'] = datetime.now()

    # STUFF RELATED TO COUNTRY SPECIFIC SITES
    context['site_url'] = "http://www.minrivertea.com"
    context['analytics_id'] = settings.ANALYTICS_ID
    context['mailchimp_list_id'] = settings.MAILCHIMP_LIST_ID

    # TEA OF THE MONTH
    try:
        totm = Product.objects.filter(totm__month=datetime.now().month,
                                      is_active=True)[0]
    except IndexError:
        totm = None
    context['totm'] = totm

    if get_language() == 'de':
        context['mailchimp_list_id'] = settings.GERMAN_MAILCHIMP_LIST_ID

    context['site_name'] = settings.SITE_NAME  # the loose non-techy name

    # GET THE NAVIGATIONS
    context['main_nav'] = Category.objects.filter(
        is_navigation_item=True).order_by('list_order')
    context['top_nav'] = Page.objects.filter(
        is_top_nav=True).order_by('list_order')

    # REGIONAL STUFF
    context['region'] = _get_region(request)
    if context['region'] == 'US':
        context['weight_unit'] = 'oz'
    else:
        context['weight_unit'] = 'g'

    # currency stuff
    context['currency'] = _get_currency(request)

    # AFFILIATE STUFF
    if settings.AFFILIATE_SESSION_KEY in request.session:
        context['affiliate_session'] = True

    if request.GET.get(settings.AFFILIATE_URL_VARIABLE):
        context[
            'landing_page'] = True  # TODO we should change this to specify which landing page it shoudl show

    # CHANGE THE BASE TEMPLATE FOR ADMIN

    if '/admin-stuff/' in request.path:
        base_template = settings.BASE_TEMPLATE_ADMIN
    else:
        base_template = settings.BASE_TEMPLATE
    context['base_template'] = base_template

    # BASKET STUFF
    try:
        basket = Basket.objects.get(id=request.session['BASKET_ID'])
    except:
        basket = None

    try:
        context['basket_quantity'] = request.session['BASKET_QUANTITY']
        context['basket_amount'] = request.session['BASKET_AMOUNT']
    except:
        basket = _get_basket_value(request)
        context['basket_quantity'] = basket['basket_quantity']
        context['basket_amount'] = basket['total_price']

    return context
Example #45
0
def _get_format():
    lang = get_language()
    return Format(utils.get_locale_from_lang(lang))
Example #46
0
 def render(self, context):
     context[self.variable] = translation.get_language()
     return ''
Example #47
0
def django_settings(request):

    return {
        'LANGUAGE': get_language(),
    }
Example #48
0
 def language():
     lang = translation.get_language()
     return lang
Example #49
0
def home_real(request: HttpRequest) -> HttpResponse:
    # Before we do any real work, check if the app is banned.
    client_user_agent = request.META.get("HTTP_USER_AGENT", "")
    (insecure_desktop_app, banned_desktop_app, auto_update_broken) = is_outdated_desktop_app(
        client_user_agent)
    if banned_desktop_app:
        return render(
            request,
            'zerver/insecure_desktop_app.html',
            context={
                "auto_update_broken": auto_update_broken,
            },
        )
    (unsupported_browser, browser_name) = is_unsupported_browser(client_user_agent)
    if unsupported_browser:
        return render(
            request,
            'zerver/unsupported_browser.html',
            context={
                "browser_name": browser_name,
            },
        )

    # We need to modify the session object every two weeks or it will expire.
    # This line makes reloading the page a sufficient action to keep the
    # session alive.
    request.session.modified = True

    if request.user.is_authenticated:
        user_profile = request.user
    else:  # nocoverage
        # This code path should not be reachable because of zulip_login_required above.
        user_profile = None

    # If a user hasn't signed the current Terms of Service, send them there
    if need_accept_tos(user_profile):
        return accounts_accept_terms(request)

    narrow, narrow_stream, narrow_topic = detect_narrowed_window(request, user_profile)

    client_capabilities = {
        'notification_settings_null': True,
        'bulk_message_deletion': True,
        'user_avatar_url_field_optional': True,
    }

    register_ret = do_events_register(user_profile, request.client,
                                      apply_markdown=True, client_gravatar=True,
                                      slim_presence=True,
                                      client_capabilities=client_capabilities,
                                      narrow=narrow)
    update_last_reminder(user_profile)

    if user_profile is not None:
        first_in_realm = realm_user_count(user_profile.realm) == 1
        # If you are the only person in the realm and you didn't invite
        # anyone, we'll continue to encourage you to do so on the frontend.
        prompt_for_invites = (
            first_in_realm and
            not PreregistrationUser.objects.filter(referred_by=user_profile).count()
        )
        needs_tutorial = user_profile.tutorial_status == UserProfile.TUTORIAL_WAITING

    else:  # nocoverage
        first_in_realm = False
        prompt_for_invites = False
        # The current tutorial doesn't super make sense for logged-out users.
        needs_tutorial = False

    furthest_read_time = get_furthest_read_time(user_profile)

    # We pick a language for the user as follows:
    # * First priority is the language in the URL, for debugging.
    # * If not in the URL, we use the language from the user's settings.
    request_language = translation.get_language_from_path(request.path_info)
    if request_language is None:
        request_language = register_ret['default_language']
    translation.activate(request_language)
    # We also save the language to the user's session, so that
    # something reasonable will happen in logged-in portico pages.
    request.session[translation.LANGUAGE_SESSION_KEY] = translation.get_language()

    two_fa_enabled = settings.TWO_FACTOR_AUTHENTICATION_ENABLED and user_profile is not None

    # Pass parameters to the client-side JavaScript code.
    # These end up in a global JavaScript Object named 'page_params'.
    page_params = dict(
        # Server settings.
        debug_mode                      = settings.DEBUG,
        test_suite                      = settings.TEST_SUITE,
        poll_timeout                    = settings.POLL_TIMEOUT,
        insecure_desktop_app            = insecure_desktop_app,
        login_page                      = settings.HOME_NOT_LOGGED_IN,
        root_domain_uri                 = settings.ROOT_DOMAIN_URI,
        save_stacktraces                = settings.SAVE_FRONTEND_STACKTRACES,
        warn_no_email                   = settings.WARN_NO_EMAIL,
        search_pills_enabled            = settings.SEARCH_PILLS_ENABLED,

        # Misc. extra data.
        initial_servertime    = time.time(),  # Used for calculating relative presence age
        default_language_name = get_language_name(register_ret['default_language']),
        language_list_dbl_col = get_language_list_for_templates(register_ret['default_language']),
        language_list         = get_language_list(),
        needs_tutorial        = needs_tutorial,
        first_in_realm        = first_in_realm,
        prompt_for_invites    = prompt_for_invites,
        furthest_read_time    = furthest_read_time,
        has_mobile_devices    = user_profile is not None and num_push_devices_for_user(user_profile) > 0,
        bot_types             = get_bot_types(user_profile),
        two_fa_enabled        = two_fa_enabled,
        # Adding two_fa_enabled as condition saves us 3 queries when
        # 2FA is not enabled.
        two_fa_enabled_user   = two_fa_enabled and bool(default_device(user_profile)),
    )

    undesired_register_ret_fields = [
        'streams',
    ]
    for field_name in set(register_ret.keys()) - set(undesired_register_ret_fields):
        page_params[field_name] = register_ret[field_name]

    if narrow_stream is not None:
        # In narrow_stream context, initial pointer is just latest message
        recipient = narrow_stream.recipient
        try:
            max_message_id = Message.objects.filter(recipient=recipient).order_by('id').reverse()[0].id
        except IndexError:
            max_message_id = -1
        page_params["narrow_stream"] = narrow_stream.name
        if narrow_topic is not None:
            page_params["narrow_topic"] = narrow_topic
        page_params["narrow"] = [dict(operator=term[0], operand=term[1]) for term in narrow]
        page_params["max_message_id"] = max_message_id
        page_params["enable_desktop_notifications"] = False

    statsd.incr('views.home')
    show_invites, show_add_streams = compute_show_invites_and_add_streams(user_profile)

    show_billing = False
    show_plans = False
    if settings.CORPORATE_ENABLED and user_profile is not None:
        from corporate.models import CustomerPlan, get_customer_by_realm
        if user_profile.has_billing_access:
            customer = get_customer_by_realm(user_profile.realm)
            if customer is not None:
                if customer.sponsorship_pending:
                    show_billing = True
                elif CustomerPlan.objects.filter(customer=customer).exists():
                    show_billing = True

        if user_profile.realm.plan_type == Realm.LIMITED:
            show_plans = True

    request._log_data['extra'] = "[{}]".format(register_ret["queue_id"])

    page_params['translation_data'] = {}
    if request_language != 'en':
        page_params['translation_data'] = get_language_translation_data(request_language)

    csp_nonce = generate_random_token(48)
    if user_profile is not None:
        color_scheme = user_profile.color_scheme
        is_guest = user_profile.is_guest
        is_realm_owner = user_profile.is_realm_owner
        is_realm_admin = user_profile.is_realm_admin
        show_webathena = user_profile.realm.webathena_enabled
    else:  # nocoverage
        color_scheme = UserProfile.COLOR_SCHEME_AUTOMATIC
        is_guest = False
        is_realm_admin = False
        is_realm_owner = False
        show_webathena = False

    navbar_logo_url = compute_navbar_logo_url(page_params)

    response = render(request, 'zerver/app/index.html',
                      context={'user_profile': user_profile,
                               'page_params': page_params,
                               'csp_nonce': csp_nonce,
                               'search_pills_enabled': settings.SEARCH_PILLS_ENABLED,
                               'show_invites': show_invites,
                               'show_add_streams': show_add_streams,
                               'show_billing': show_billing,
                               'corporate_enabled': settings.CORPORATE_ENABLED,
                               'show_plans': show_plans,
                               'is_owner': is_realm_owner,
                               'is_admin': is_realm_admin,
                               'is_guest': is_guest,
                               'color_scheme': color_scheme,
                               'navbar_logo_url': navbar_logo_url,
                               'show_webathena': show_webathena,
                               'embedded': narrow_stream is not None,
                               'invite_as': PreregistrationUser.INVITE_AS,
                               'max_file_upload_size_mib': settings.MAX_FILE_UPLOAD_SIZE,
                               })
    patch_cache_control(response, no_cache=True, no_store=True, must_revalidate=True)
    return response
Example #50
0
 def process_response(self, request, response):
     if 'Content-Language' not in response:
         response['Content-Language'] = translation.get_language()
     translation.deactivate()
     return response
 def get_kml_url(self, obj):
     return reverse('sensitivity:sensitivearea_kml_detail', kwargs={'lang': get_language(), 'pk': obj.pk})
Example #52
0
 def active_contentions(self):
     language = normalize_language_code(get_language())
     return self.contentions.filter(
         is_published=True,
         language=language
     ).order_by('?')
Example #53
0
 def process_response(self, request, response):
     if settings.USE_I18N and request.path.find('/admin') != 0 and response.status_code == 200 and 'text/html' in \
             response['Content-Type']:
         response.set_cookie(settings.LANGUAGE_COOKIE_NAME, get_language())
     return response
Example #54
0
def get_current_language(context):
    from django.utils.translation import get_language

    return get_language()
Example #55
0
 def get_map_image_path(self):
     basefolder = os.path.join(settings.MEDIA_ROOT, 'maps')
     if not os.path.exists(basefolder):
         os.makedirs(basefolder)
     return os.path.join(basefolder, '%s-%s-%s.png' % (self._meta.module_name, self.pk, get_language()))
Example #56
0
def get_real_fieldname(field, lang=None):
    """ append lang to base field name. Use active or fallback language if lang is None """
    if lang is None:
        lang = get_language() or fallback_language()
        lang = lang.split('-')[0] # both 'en-US' and 'en' -> 'en'
    return str('%s_%s' % (field, lang))
Example #57
0
 def get_context_data(self, **kwargs):
     activate(self.language)
     context = super(TranslatedTemplateView,
                     self).get_context_data(**kwargs)
     context['current_language'] = get_language()
     return context
Example #58
0
 def get_document_public_url(self):
     """ Override ``geotrek.common.mixins.PublishableMixin``
     """
     return ('trekking:poi_document_public', [], {'lang': get_language(), 'pk': self.pk, 'slug': self.slug})
Example #59
0
 def __set__(self, instance, value):
     if isinstance(value, six.string_types):
         language = translation.get_language() or settings.LANGUAGE_CODE
         self.__get__(instance).set(language, value)  # pylint: disable=no-member
     else:
         instance.__dict__[self.field.name] = value
Example #60
0
 def get_map_image_url(self):
     return ('trekking:trek_map_image', [], {'pk': str(self.pk), 'lang': get_language()})