2015-01-28 20:35:27 +08:00
|
|
|
import gettext as gettext_module
|
2013-07-29 21:50:58 +08:00
|
|
|
import importlib
|
2013-04-14 22:55:17 +08:00
|
|
|
import json
|
2009-12-23 01:58:49 +08:00
|
|
|
import os
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
from django import http
|
2013-12-24 19:25:17 +08:00
|
|
|
from django.apps import apps
|
2009-03-19 00:55:59 +08:00
|
|
|
from django.conf import settings
|
2015-03-12 16:32:29 +08:00
|
|
|
from django.core.urlresolvers import translate_url
|
2015-02-23 02:14:05 +08:00
|
|
|
from django.template import Context, Engine
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.utils import six
|
2012-12-08 18:13:52 +08:00
|
|
|
from django.utils._os import upath
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.utils.encoding import smart_text
|
|
|
|
from django.utils.formats import get_format, get_format_modules
|
2012-11-18 05:00:53 +08:00
|
|
|
from django.utils.http import is_safe_url
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.utils.translation import (
|
|
|
|
LANGUAGE_SESSION_KEY, check_for_language, get_language, to_locale,
|
|
|
|
)
|
2005-11-04 12:59:46 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2005-11-04 12:59:46 +08:00
|
|
|
def set_language(request):
|
|
|
|
"""
|
|
|
|
Redirect to a given url while setting the chosen language in the
|
|
|
|
session or cookie. The url and the language code need to be
|
2007-09-14 15:33:45 +08:00
|
|
|
specified in the request parameters.
|
|
|
|
|
|
|
|
Since this view changes how the user will see the rest of the site, it must
|
|
|
|
only be accessed as a POST request. If called as a GET request, it will
|
|
|
|
redirect to the page in the request (the 'next' parameter) without changing
|
|
|
|
any state.
|
2005-11-04 12:59:46 +08:00
|
|
|
"""
|
2013-10-16 04:36:49 +08:00
|
|
|
next = request.POST.get('next', request.GET.get('next'))
|
2012-11-18 05:00:53 +08:00
|
|
|
if not is_safe_url(url=next, host=request.get_host()):
|
|
|
|
next = request.META.get('HTTP_REFERER')
|
|
|
|
if not is_safe_url(url=next, host=request.get_host()):
|
|
|
|
next = '/'
|
2006-05-02 09:31:56 +08:00
|
|
|
response = http.HttpResponseRedirect(next)
|
2007-09-14 15:33:45 +08:00
|
|
|
if request.method == 'POST':
|
|
|
|
lang_code = request.POST.get('language', None)
|
|
|
|
if lang_code and check_for_language(lang_code):
|
2015-03-12 16:32:29 +08:00
|
|
|
next_trans = translate_url(next, lang_code)
|
|
|
|
if next_trans != next:
|
|
|
|
response = http.HttpResponseRedirect(next_trans)
|
2007-09-14 15:33:45 +08:00
|
|
|
if hasattr(request, 'session'):
|
2014-02-22 21:27:57 +08:00
|
|
|
request.session[LANGUAGE_SESSION_KEY] = lang_code
|
2007-09-14 15:33:45 +08:00
|
|
|
else:
|
2013-05-19 18:20:34 +08:00
|
|
|
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code,
|
|
|
|
max_age=settings.LANGUAGE_COOKIE_AGE,
|
|
|
|
path=settings.LANGUAGE_COOKIE_PATH,
|
|
|
|
domain=settings.LANGUAGE_COOKIE_DOMAIN)
|
2005-11-04 12:59:46 +08:00
|
|
|
return response
|
2005-12-04 20:06:16 +08:00
|
|
|
|
2013-04-14 22:55:17 +08:00
|
|
|
|
2009-12-23 01:58:49 +08:00
|
|
|
def get_formats():
|
|
|
|
"""
|
2009-12-31 06:12:16 +08:00
|
|
|
Returns all formats strings required for i18n to work
|
2009-12-23 01:58:49 +08:00
|
|
|
"""
|
2009-12-31 06:12:16 +08:00
|
|
|
FORMAT_SETTINGS = (
|
|
|
|
'DATE_FORMAT', 'DATETIME_FORMAT', 'TIME_FORMAT',
|
2009-12-23 01:58:49 +08:00
|
|
|
'YEAR_MONTH_FORMAT', 'MONTH_DAY_FORMAT', 'SHORT_DATE_FORMAT',
|
|
|
|
'SHORT_DATETIME_FORMAT', 'FIRST_DAY_OF_WEEK', 'DECIMAL_SEPARATOR',
|
2009-12-31 06:12:16 +08:00
|
|
|
'THOUSAND_SEPARATOR', 'NUMBER_GROUPING',
|
|
|
|
'DATE_INPUT_FORMATS', 'TIME_INPUT_FORMATS', 'DATETIME_INPUT_FORMATS'
|
|
|
|
)
|
2009-12-23 01:58:49 +08:00
|
|
|
result = {}
|
2009-12-31 06:12:16 +08:00
|
|
|
for module in [settings] + get_format_modules(reverse=True):
|
2009-12-23 01:58:49 +08:00
|
|
|
for attr in FORMAT_SETTINGS:
|
2011-02-04 21:52:36 +08:00
|
|
|
result[attr] = get_format(attr)
|
2013-04-14 22:55:17 +08:00
|
|
|
formats = {}
|
2010-01-04 10:28:34 +08:00
|
|
|
for k, v in result.items():
|
2012-07-20 20:22:00 +08:00
|
|
|
if isinstance(v, (six.string_types, int)):
|
2013-04-14 22:55:17 +08:00
|
|
|
formats[k] = smart_text(v)
|
2010-01-04 10:28:34 +08:00
|
|
|
elif isinstance(v, (tuple, list)):
|
2013-04-14 22:55:17 +08:00
|
|
|
formats[k] = [smart_text(value) for value in v]
|
|
|
|
return formats
|
2005-12-04 20:06:16 +08:00
|
|
|
|
|
|
|
|
2013-04-14 22:55:17 +08:00
|
|
|
js_catalog_template = r"""
|
|
|
|
{% autoescape off %}
|
|
|
|
(function (globals) {
|
2005-12-04 20:06:16 +08:00
|
|
|
|
2013-04-14 22:55:17 +08:00
|
|
|
var django = globals.django || (globals.django = {});
|
2010-01-04 10:28:34 +08:00
|
|
|
|
2013-04-14 22:55:17 +08:00
|
|
|
{% if plural %}
|
|
|
|
django.pluralidx = function (n) {
|
|
|
|
var v={{ plural }};
|
|
|
|
if (typeof(v) == 'boolean') {
|
|
|
|
return v ? 1 : 0;
|
|
|
|
} else {
|
|
|
|
return v;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
{% else %}
|
|
|
|
django.pluralidx = function (count) { return (count == 1) ? 0 : 1; };
|
|
|
|
{% endif %}
|
2010-01-04 10:28:34 +08:00
|
|
|
|
2013-04-14 22:55:17 +08:00
|
|
|
{% if catalog_str %}
|
|
|
|
/* gettext library */
|
2010-01-04 10:28:34 +08:00
|
|
|
|
2013-04-14 22:55:17 +08:00
|
|
|
django.catalog = {{ catalog_str }};
|
2010-01-04 10:28:34 +08:00
|
|
|
|
2013-04-14 22:55:17 +08:00
|
|
|
django.gettext = function (msgid) {
|
|
|
|
var value = django.catalog[msgid];
|
|
|
|
if (typeof(value) == 'undefined') {
|
|
|
|
return msgid;
|
|
|
|
} else {
|
|
|
|
return (typeof(value) == 'string') ? value : value[0];
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
django.ngettext = function (singular, plural, count) {
|
2013-10-30 21:12:27 +08:00
|
|
|
var value = django.catalog[singular];
|
2013-04-14 22:55:17 +08:00
|
|
|
if (typeof(value) == 'undefined') {
|
|
|
|
return (count == 1) ? singular : plural;
|
|
|
|
} else {
|
|
|
|
return value[django.pluralidx(count)];
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
django.gettext_noop = function (msgid) { return msgid; };
|
|
|
|
|
|
|
|
django.pgettext = function (context, msgid) {
|
|
|
|
var value = django.gettext(context + '\x04' + msgid);
|
|
|
|
if (value.indexOf('\x04') != -1) {
|
|
|
|
value = msgid;
|
|
|
|
}
|
|
|
|
return value;
|
|
|
|
};
|
|
|
|
|
|
|
|
django.npgettext = function (context, singular, plural, count) {
|
|
|
|
var value = django.ngettext(context + '\x04' + singular, context + '\x04' + plural, count);
|
|
|
|
if (value.indexOf('\x04') != -1) {
|
|
|
|
value = django.ngettext(singular, plural, count);
|
|
|
|
}
|
|
|
|
return value;
|
|
|
|
};
|
|
|
|
{% else %}
|
|
|
|
/* gettext identity library */
|
|
|
|
|
|
|
|
django.gettext = function (msgid) { return msgid; };
|
|
|
|
django.ngettext = function (singular, plural, count) { return (count == 1) ? singular : plural; };
|
|
|
|
django.gettext_noop = function (msgid) { return msgid; };
|
|
|
|
django.pgettext = function (context, msgid) { return msgid; };
|
|
|
|
django.npgettext = function (context, singular, plural, count) { return (count == 1) ? singular : plural; };
|
|
|
|
{% endif %}
|
|
|
|
|
|
|
|
django.interpolate = function (fmt, obj, named) {
|
|
|
|
if (named) {
|
|
|
|
return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])});
|
|
|
|
} else {
|
|
|
|
return fmt.replace(/%s/g, function(match){return String(obj.shift())});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
/* formatting library */
|
|
|
|
|
|
|
|
django.formats = {{ formats_str }};
|
|
|
|
|
|
|
|
django.get_format = function (format_type) {
|
|
|
|
var value = django.formats[format_type];
|
2010-01-04 10:28:34 +08:00
|
|
|
if (typeof(value) == 'undefined') {
|
2012-04-26 09:03:03 +08:00
|
|
|
return format_type;
|
2010-01-04 10:28:34 +08:00
|
|
|
} else {
|
|
|
|
return value;
|
|
|
|
}
|
2013-04-14 22:55:17 +08:00
|
|
|
};
|
2005-12-04 20:06:16 +08:00
|
|
|
|
2013-04-14 22:55:17 +08:00
|
|
|
/* add to global namespace */
|
|
|
|
globals.pluralidx = django.pluralidx;
|
|
|
|
globals.gettext = django.gettext;
|
|
|
|
globals.ngettext = django.ngettext;
|
|
|
|
globals.gettext_noop = django.gettext_noop;
|
|
|
|
globals.pgettext = django.pgettext;
|
|
|
|
globals.npgettext = django.npgettext;
|
|
|
|
globals.interpolate = django.interpolate;
|
|
|
|
globals.get_format = django.get_format;
|
2005-12-04 20:06:16 +08:00
|
|
|
|
2013-04-14 22:55:17 +08:00
|
|
|
}(this));
|
|
|
|
{% endautoescape %}
|
2005-12-04 20:06:16 +08:00
|
|
|
"""
|
|
|
|
|
2013-04-14 22:55:17 +08:00
|
|
|
|
|
|
|
def render_javascript_catalog(catalog=None, plural=None):
|
2015-02-23 02:14:05 +08:00
|
|
|
template = Engine().from_string(js_catalog_template)
|
2013-04-14 22:55:17 +08:00
|
|
|
indent = lambda s: s.replace('\n', '\n ')
|
|
|
|
context = Context({
|
|
|
|
'catalog_str': indent(json.dumps(
|
|
|
|
catalog, sort_keys=True, indent=2)) if catalog else None,
|
|
|
|
'formats_str': indent(json.dumps(
|
|
|
|
get_formats(), sort_keys=True, indent=2)),
|
|
|
|
'plural': plural,
|
|
|
|
})
|
|
|
|
|
|
|
|
return http.HttpResponse(template.render(context), 'text/javascript')
|
|
|
|
|
2008-03-24 21:27:19 +08:00
|
|
|
|
2013-05-18 19:20:52 +08:00
|
|
|
def get_javascript_catalog(locale, domain, packages):
|
2013-05-05 21:52:07 +08:00
|
|
|
default_locale = to_locale(settings.LANGUAGE_CODE)
|
2013-12-24 19:25:17 +08:00
|
|
|
app_configs = apps.get_app_configs()
|
2013-12-19 22:57:23 +08:00
|
|
|
allowable_packages = set(app_config.name for app_config in app_configs)
|
|
|
|
allowable_packages.add('django.conf')
|
|
|
|
packages = [p for p in packages if p in allowable_packages]
|
2005-12-04 20:06:16 +08:00
|
|
|
t = {}
|
|
|
|
paths = []
|
2010-12-13 21:52:52 +08:00
|
|
|
en_selected = locale.startswith('en')
|
|
|
|
en_catalog_missing = True
|
2011-02-08 02:48:40 +08:00
|
|
|
# paths of requested packages
|
2005-12-04 20:06:16 +08:00
|
|
|
for package in packages:
|
2009-03-19 00:55:59 +08:00
|
|
|
p = importlib.import_module(package)
|
2012-12-08 18:13:52 +08:00
|
|
|
path = os.path.join(os.path.dirname(upath(p.__file__)), 'locale')
|
2005-12-04 20:06:16 +08:00
|
|
|
paths.append(path)
|
2011-02-08 02:48:40 +08:00
|
|
|
# add the filesystem paths listed in the LOCALE_PATHS setting
|
2015-01-22 00:55:57 +08:00
|
|
|
paths.extend(reversed(settings.LOCALE_PATHS))
|
2011-02-08 02:48:40 +08:00
|
|
|
# first load all english languages files for defaults
|
|
|
|
for path in paths:
|
2007-11-30 01:29:54 +08:00
|
|
|
try:
|
|
|
|
catalog = gettext_module.translation(domain, path, ['en'])
|
|
|
|
t.update(catalog._catalog)
|
|
|
|
except IOError:
|
|
|
|
pass
|
2010-12-13 21:52:52 +08:00
|
|
|
else:
|
|
|
|
# 'en' is the selected language and at least one of the packages
|
|
|
|
# listed in `packages` has an 'en' catalog
|
|
|
|
if en_selected:
|
|
|
|
en_catalog_missing = False
|
2005-12-07 04:30:56 +08:00
|
|
|
# next load the settings.LANGUAGE_CODE translations if it isn't english
|
|
|
|
if default_locale != 'en':
|
|
|
|
for path in paths:
|
|
|
|
try:
|
|
|
|
catalog = gettext_module.translation(domain, path, [default_locale])
|
2006-01-19 09:06:12 +08:00
|
|
|
except IOError:
|
2005-12-07 04:30:56 +08:00
|
|
|
catalog = None
|
|
|
|
if catalog is not None:
|
|
|
|
t.update(catalog._catalog)
|
|
|
|
# last load the currently selected language, if it isn't identical to the default.
|
2005-12-04 20:06:16 +08:00
|
|
|
if locale != default_locale:
|
2010-12-13 21:52:52 +08:00
|
|
|
# If the currently selected language is English but it doesn't have a
|
|
|
|
# translation catalog (presumably due to being the language translated
|
|
|
|
# from) then a wrong language catalog might have been loaded in the
|
|
|
|
# previous step. It needs to be discarded.
|
|
|
|
if en_selected and en_catalog_missing:
|
2010-02-05 09:43:13 +08:00
|
|
|
t = {}
|
|
|
|
else:
|
2010-05-13 21:29:31 +08:00
|
|
|
locale_t = {}
|
2010-02-05 09:43:13 +08:00
|
|
|
for path in paths:
|
|
|
|
try:
|
|
|
|
catalog = gettext_module.translation(domain, path, [locale])
|
|
|
|
except IOError:
|
|
|
|
catalog = None
|
|
|
|
if catalog is not None:
|
2010-05-13 21:29:31 +08:00
|
|
|
locale_t.update(catalog._catalog)
|
|
|
|
if locale_t:
|
|
|
|
t = locale_t
|
2005-12-04 20:06:16 +08:00
|
|
|
plural = None
|
2007-04-26 21:30:48 +08:00
|
|
|
if '' in t:
|
2005-12-07 04:30:56 +08:00
|
|
|
for l in t[''].split('\n'):
|
|
|
|
if l.startswith('Plural-Forms:'):
|
2013-04-14 22:55:17 +08:00
|
|
|
plural = l.split(':', 1)[1].strip()
|
2005-12-04 20:06:16 +08:00
|
|
|
if plural is not None:
|
|
|
|
# this should actually be a compiled function of a typical plural-form:
|
2014-09-04 20:15:09 +08:00
|
|
|
# Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 :
|
|
|
|
# n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
|
2013-04-14 22:55:17 +08:00
|
|
|
plural = [el.strip() for el in plural.split(';') if el.strip().startswith('plural=')][0].split('=', 1)[1]
|
|
|
|
|
2005-12-04 20:06:16 +08:00
|
|
|
pdict = {}
|
2013-04-14 22:55:17 +08:00
|
|
|
maxcnts = {}
|
|
|
|
catalog = {}
|
2005-12-04 20:06:16 +08:00
|
|
|
for k, v in t.items():
|
|
|
|
if k == '':
|
|
|
|
continue
|
2012-07-20 20:22:00 +08:00
|
|
|
if isinstance(k, six.string_types):
|
2013-04-14 22:55:17 +08:00
|
|
|
catalog[k] = v
|
2009-12-31 06:12:16 +08:00
|
|
|
elif isinstance(k, tuple):
|
2013-04-14 22:55:17 +08:00
|
|
|
msgid = k[0]
|
|
|
|
cnt = k[1]
|
|
|
|
maxcnts[msgid] = max(cnt, maxcnts.get(msgid, 0))
|
|
|
|
pdict.setdefault(msgid, {})[cnt] = v
|
2005-12-04 20:06:16 +08:00
|
|
|
else:
|
2010-01-11 02:36:20 +08:00
|
|
|
raise TypeError(k)
|
2009-12-23 01:58:49 +08:00
|
|
|
for k, v in pdict.items():
|
2013-04-14 22:55:17 +08:00
|
|
|
catalog[k] = [v.get(i, '') for i in range(maxcnts[msgid] + 1)]
|
|
|
|
|
2013-05-18 19:20:52 +08:00
|
|
|
return catalog, plural
|
|
|
|
|
|
|
|
|
|
|
|
def null_javascript_catalog(request, domain=None, packages=None):
|
|
|
|
"""
|
|
|
|
Returns "identity" versions of the JavaScript i18n functions -- i.e.,
|
|
|
|
versions that don't actually do anything.
|
|
|
|
"""
|
|
|
|
return render_javascript_catalog()
|
|
|
|
|
|
|
|
|
|
|
|
def javascript_catalog(request, domain='djangojs', packages=None):
|
|
|
|
"""
|
|
|
|
Returns the selected language catalog as a javascript library.
|
|
|
|
|
|
|
|
Receives the list of packages to check for translations in the
|
|
|
|
packages parameter either from an infodict or as a +-delimited
|
|
|
|
string from the request. Default is 'django.conf'.
|
|
|
|
|
|
|
|
Additionally you can override the gettext domain for this view,
|
|
|
|
but usually you don't want to do that, as JavaScript messages
|
|
|
|
go to the djangojs domain. But this might be needed if you
|
|
|
|
deliver your JavaScript source from Django templates.
|
|
|
|
"""
|
|
|
|
locale = to_locale(get_language())
|
|
|
|
|
|
|
|
if request.GET and 'language' in request.GET:
|
|
|
|
if check_for_language(request.GET['language']):
|
|
|
|
locale = to_locale(request.GET['language'])
|
|
|
|
|
|
|
|
if packages is None:
|
|
|
|
packages = ['django.conf']
|
|
|
|
if isinstance(packages, six.string_types):
|
|
|
|
packages = packages.split('+')
|
|
|
|
|
|
|
|
catalog, plural = get_javascript_catalog(locale, domain, packages)
|
2013-04-14 22:55:17 +08:00
|
|
|
return render_javascript_catalog(catalog, plural)
|