Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

trans_real.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. """Translation helper functions."""
  2. import functools
  3. import gettext as gettext_module
  4. import os
  5. import re
  6. import sys
  7. import warnings
  8. from collections import OrderedDict
  9. from threading import local
  10. from django.apps import apps
  11. from django.conf import settings
  12. from django.conf.locale import LANG_INFO
  13. from django.core.exceptions import AppRegistryNotReady
  14. from django.core.signals import setting_changed
  15. from django.dispatch import receiver
  16. from django.utils.safestring import SafeData, mark_safe
  17. from . import LANGUAGE_SESSION_KEY, to_language, to_locale
  18. # Translations are cached in a dictionary for every language.
  19. # The active translations are stored by threadid to make them thread local.
  20. _translations = {}
  21. _active = local()
  22. # The default translation is based on the settings file.
  23. _default = None
  24. # magic gettext number to separate context from message
  25. CONTEXT_SEPARATOR = "\x04"
  26. # Format of Accept-Language header values. From RFC 2616, section 14.4 and 3.9
  27. # and RFC 3066, section 2.1
  28. accept_language_re = re.compile(r'''
  29. ([A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*|\*) # "en", "en-au", "x-y-z", "es-419", "*"
  30. (?:\s*;\s*q=(0(?:\.\d{,3})?|1(?:\.0{,3})?))? # Optional "q=1.00", "q=0.8"
  31. (?:\s*,\s*|$) # Multiple accepts per header.
  32. ''', re.VERBOSE)
  33. language_code_re = re.compile(
  34. r'^[a-z]{1,8}(?:-[a-z0-9]{1,8})*(?:@[a-z0-9]{1,20})?$',
  35. re.IGNORECASE
  36. )
  37. language_code_prefix_re = re.compile(r'^/(\w+([@-]\w+)?)(/|$)')
  38. @receiver(setting_changed)
  39. def reset_cache(**kwargs):
  40. """
  41. Reset global state when LANGUAGES setting has been changed, as some
  42. languages should no longer be accepted.
  43. """
  44. if kwargs['setting'] in ('LANGUAGES', 'LANGUAGE_CODE'):
  45. check_for_language.cache_clear()
  46. get_languages.cache_clear()
  47. get_supported_language_variant.cache_clear()
  48. class DjangoTranslation(gettext_module.GNUTranslations):
  49. """
  50. Set up the GNUTranslations context with regard to output charset.
  51. This translation object will be constructed out of multiple GNUTranslations
  52. objects by merging their catalogs. It will construct an object for the
  53. requested language and add a fallback to the default language, if it's
  54. different from the requested language.
  55. """
  56. domain = 'django'
  57. def __init__(self, language, domain=None, localedirs=None):
  58. """Create a GNUTranslations() using many locale directories"""
  59. gettext_module.GNUTranslations.__init__(self)
  60. if domain is not None:
  61. self.domain = domain
  62. self.__language = language
  63. self.__to_language = to_language(language)
  64. self.__locale = to_locale(language)
  65. self._catalog = None
  66. # If a language doesn't have a catalog, use the Germanic default for
  67. # pluralization: anything except one is pluralized.
  68. self.plural = lambda n: int(n != 1)
  69. if self.domain == 'django':
  70. if localedirs is not None:
  71. # A module-level cache is used for caching 'django' translations
  72. warnings.warn("localedirs is ignored when domain is 'django'.", RuntimeWarning)
  73. localedirs = None
  74. self._init_translation_catalog()
  75. if localedirs:
  76. for localedir in localedirs:
  77. translation = self._new_gnu_trans(localedir)
  78. self.merge(translation)
  79. else:
  80. self._add_installed_apps_translations()
  81. self._add_local_translations()
  82. if self.__language == settings.LANGUAGE_CODE and self.domain == 'django' and self._catalog is None:
  83. # default lang should have at least one translation file available.
  84. raise IOError("No translation files found for default language %s." % settings.LANGUAGE_CODE)
  85. self._add_fallback(localedirs)
  86. if self._catalog is None:
  87. # No catalogs found for this language, set an empty catalog.
  88. self._catalog = {}
  89. def __repr__(self):
  90. return "<DjangoTranslation lang:%s>" % self.__language
  91. def _new_gnu_trans(self, localedir, use_null_fallback=True):
  92. """
  93. Return a mergeable gettext.GNUTranslations instance.
  94. A convenience wrapper. By default gettext uses 'fallback=False'.
  95. Using param `use_null_fallback` to avoid confusion with any other
  96. references to 'fallback'.
  97. """
  98. return gettext_module.translation(
  99. domain=self.domain,
  100. localedir=localedir,
  101. languages=[self.__locale],
  102. codeset='utf-8',
  103. fallback=use_null_fallback,
  104. )
  105. def _init_translation_catalog(self):
  106. """Create a base catalog using global django translations."""
  107. settingsfile = sys.modules[settings.__module__].__file__
  108. localedir = os.path.join(os.path.dirname(settingsfile), 'locale')
  109. translation = self._new_gnu_trans(localedir)
  110. self.merge(translation)
  111. def _add_installed_apps_translations(self):
  112. """Merge translations from each installed app."""
  113. try:
  114. app_configs = reversed(list(apps.get_app_configs()))
  115. except AppRegistryNotReady:
  116. raise AppRegistryNotReady(
  117. "The translation infrastructure cannot be initialized before the "
  118. "apps registry is ready. Check that you don't make non-lazy "
  119. "gettext calls at import time.")
  120. for app_config in app_configs:
  121. localedir = os.path.join(app_config.path, 'locale')
  122. if os.path.exists(localedir):
  123. translation = self._new_gnu_trans(localedir)
  124. self.merge(translation)
  125. def _add_local_translations(self):
  126. """Merge translations defined in LOCALE_PATHS."""
  127. for localedir in reversed(settings.LOCALE_PATHS):
  128. translation = self._new_gnu_trans(localedir)
  129. self.merge(translation)
  130. def _add_fallback(self, localedirs=None):
  131. """Set the GNUTranslations() fallback with the default language."""
  132. # Don't set a fallback for the default language or any English variant
  133. # (as it's empty, so it'll ALWAYS fall back to the default language)
  134. if self.__language == settings.LANGUAGE_CODE or self.__language.startswith('en'):
  135. return
  136. if self.domain == 'django':
  137. # Get from cache
  138. default_translation = translation(settings.LANGUAGE_CODE)
  139. else:
  140. default_translation = DjangoTranslation(
  141. settings.LANGUAGE_CODE, domain=self.domain, localedirs=localedirs
  142. )
  143. self.add_fallback(default_translation)
  144. def merge(self, other):
  145. """Merge another translation into this catalog."""
  146. if not getattr(other, '_catalog', None):
  147. return # NullTranslations() has no _catalog
  148. if self._catalog is None:
  149. # Take plural and _info from first catalog found (generally Django's).
  150. self.plural = other.plural
  151. self._info = other._info.copy()
  152. self._catalog = other._catalog.copy()
  153. else:
  154. self._catalog.update(other._catalog)
  155. if other._fallback:
  156. self.add_fallback(other._fallback)
  157. def language(self):
  158. """Return the translation language."""
  159. return self.__language
  160. def to_language(self):
  161. """Return the translation language name."""
  162. return self.__to_language
  163. def translation(language):
  164. """
  165. Return a translation object in the default 'django' domain.
  166. """
  167. global _translations
  168. if language not in _translations:
  169. _translations[language] = DjangoTranslation(language)
  170. return _translations[language]
  171. def activate(language):
  172. """
  173. Fetch the translation object for a given language and install it as the
  174. current translation object for the current thread.
  175. """
  176. if not language:
  177. return
  178. _active.value = translation(language)
  179. def deactivate():
  180. """
  181. Uninstall the active translation object so that further _() calls resolve
  182. to the default translation object.
  183. """
  184. if hasattr(_active, "value"):
  185. del _active.value
  186. def deactivate_all():
  187. """
  188. Make the active translation object a NullTranslations() instance. This is
  189. useful when we want delayed translations to appear as the original string
  190. for some reason.
  191. """
  192. _active.value = gettext_module.NullTranslations()
  193. _active.value.to_language = lambda *args: None
  194. def get_language():
  195. """Return the currently selected language."""
  196. t = getattr(_active, "value", None)
  197. if t is not None:
  198. try:
  199. return t.to_language()
  200. except AttributeError:
  201. pass
  202. # If we don't have a real translation object, assume it's the default language.
  203. return settings.LANGUAGE_CODE
  204. def get_language_bidi():
  205. """
  206. Return selected language's BiDi layout.
  207. * False = left-to-right layout
  208. * True = right-to-left layout
  209. """
  210. lang = get_language()
  211. if lang is None:
  212. return False
  213. else:
  214. base_lang = get_language().split('-')[0]
  215. return base_lang in settings.LANGUAGES_BIDI
  216. def catalog():
  217. """
  218. Return the current active catalog for further processing.
  219. This can be used if you need to modify the catalog or want to access the
  220. whole message catalog instead of just translating one string.
  221. """
  222. global _default
  223. t = getattr(_active, "value", None)
  224. if t is not None:
  225. return t
  226. if _default is None:
  227. _default = translation(settings.LANGUAGE_CODE)
  228. return _default
  229. def gettext(message):
  230. """
  231. Translate the 'message' string. It uses the current thread to find the
  232. translation object to use. If no current translation is activated, the
  233. message will be run through the default translation object.
  234. """
  235. global _default
  236. eol_message = message.replace('\r\n', '\n').replace('\r', '\n')
  237. if eol_message:
  238. _default = _default or translation(settings.LANGUAGE_CODE)
  239. translation_object = getattr(_active, "value", _default)
  240. result = translation_object.gettext(eol_message)
  241. else:
  242. # Return an empty value of the corresponding type if an empty message
  243. # is given, instead of metadata, which is the default gettext behavior.
  244. result = type(message)('')
  245. if isinstance(message, SafeData):
  246. return mark_safe(result)
  247. return result
  248. def pgettext(context, message):
  249. msg_with_ctxt = "%s%s%s" % (context, CONTEXT_SEPARATOR, message)
  250. result = gettext(msg_with_ctxt)
  251. if CONTEXT_SEPARATOR in result:
  252. # Translation not found
  253. result = message
  254. elif isinstance(message, SafeData):
  255. result = mark_safe(result)
  256. return result
  257. def gettext_noop(message):
  258. """
  259. Mark strings for translation but don't translate them now. This can be
  260. used to store strings in global variables that should stay in the base
  261. language (because they might be used externally) and will be translated
  262. later.
  263. """
  264. return message
  265. def do_ntranslate(singular, plural, number, translation_function):
  266. global _default
  267. t = getattr(_active, "value", None)
  268. if t is not None:
  269. return getattr(t, translation_function)(singular, plural, number)
  270. if _default is None:
  271. _default = translation(settings.LANGUAGE_CODE)
  272. return getattr(_default, translation_function)(singular, plural, number)
  273. def ngettext(singular, plural, number):
  274. """
  275. Return a string of the translation of either the singular or plural,
  276. based on the number.
  277. """
  278. return do_ntranslate(singular, plural, number, 'ngettext')
  279. def npgettext(context, singular, plural, number):
  280. msgs_with_ctxt = ("%s%s%s" % (context, CONTEXT_SEPARATOR, singular),
  281. "%s%s%s" % (context, CONTEXT_SEPARATOR, plural),
  282. number)
  283. result = ngettext(*msgs_with_ctxt)
  284. if CONTEXT_SEPARATOR in result:
  285. # Translation not found
  286. result = ngettext(singular, plural, number)
  287. return result
  288. def all_locale_paths():
  289. """
  290. Return a list of paths to user-provides languages files.
  291. """
  292. globalpath = os.path.join(
  293. os.path.dirname(sys.modules[settings.__module__].__file__), 'locale')
  294. app_paths = []
  295. for app_config in apps.get_app_configs():
  296. locale_path = os.path.join(app_config.path, 'locale')
  297. if os.path.exists(locale_path):
  298. app_paths.append(locale_path)
  299. return [globalpath] + list(settings.LOCALE_PATHS) + app_paths
  300. @functools.lru_cache(maxsize=1000)
  301. def check_for_language(lang_code):
  302. """
  303. Check whether there is a global language file for the given language
  304. code. This is used to decide whether a user-provided language is
  305. available.
  306. lru_cache should have a maxsize to prevent from memory exhaustion attacks,
  307. as the provided language codes are taken from the HTTP request. See also
  308. <https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>.
  309. """
  310. # First, a quick check to make sure lang_code is well-formed (#21458)
  311. if lang_code is None or not language_code_re.search(lang_code):
  312. return False
  313. return any(
  314. gettext_module.find('django', path, [to_locale(lang_code)]) is not None
  315. for path in all_locale_paths()
  316. )
  317. @functools.lru_cache()
  318. def get_languages():
  319. """
  320. Cache of settings.LANGUAGES in an OrderedDict for easy lookups by key.
  321. """
  322. return OrderedDict(settings.LANGUAGES)
  323. @functools.lru_cache(maxsize=1000)
  324. def get_supported_language_variant(lang_code, strict=False):
  325. """
  326. Return the language code that's listed in supported languages, possibly
  327. selecting a more generic variant. Raise LookupError if nothing is found.
  328. If `strict` is False (the default), look for a country-specific variant
  329. when neither the language code nor its generic variant is found.
  330. lru_cache should have a maxsize to prevent from memory exhaustion attacks,
  331. as the provided language codes are taken from the HTTP request. See also
  332. <https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>.
  333. """
  334. if lang_code:
  335. # If 'fr-ca' is not supported, try special fallback or language-only 'fr'.
  336. possible_lang_codes = [lang_code]
  337. try:
  338. possible_lang_codes.extend(LANG_INFO[lang_code]['fallback'])
  339. except KeyError:
  340. pass
  341. generic_lang_code = lang_code.split('-')[0]
  342. possible_lang_codes.append(generic_lang_code)
  343. supported_lang_codes = get_languages()
  344. for code in possible_lang_codes:
  345. if code in supported_lang_codes and check_for_language(code):
  346. return code
  347. if not strict:
  348. # if fr-fr is not supported, try fr-ca.
  349. for supported_code in supported_lang_codes:
  350. if supported_code.startswith(generic_lang_code + '-'):
  351. return supported_code
  352. raise LookupError(lang_code)
  353. def get_language_from_path(path, strict=False):
  354. """
  355. Return the language code if there's a valid language code found in `path`.
  356. If `strict` is False (the default), look for a country-specific variant
  357. when neither the language code nor its generic variant is found.
  358. """
  359. regex_match = language_code_prefix_re.match(path)
  360. if not regex_match:
  361. return None
  362. lang_code = regex_match.group(1)
  363. try:
  364. return get_supported_language_variant(lang_code, strict=strict)
  365. except LookupError:
  366. return None
  367. def get_language_from_request(request, check_path=False):
  368. """
  369. Analyze the request to find what language the user wants the system to
  370. show. Only languages listed in settings.LANGUAGES are taken into account.
  371. If the user requests a sublanguage where we have a main language, we send
  372. out the main language.
  373. If check_path is True, the URL path prefix will be checked for a language
  374. code, otherwise this is skipped for backwards compatibility.
  375. """
  376. if check_path:
  377. lang_code = get_language_from_path(request.path_info)
  378. if lang_code is not None:
  379. return lang_code
  380. supported_lang_codes = get_languages()
  381. if hasattr(request, 'session'):
  382. lang_code = request.session.get(LANGUAGE_SESSION_KEY)
  383. if lang_code in supported_lang_codes and lang_code is not None and check_for_language(lang_code):
  384. return lang_code
  385. lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)
  386. try:
  387. return get_supported_language_variant(lang_code)
  388. except LookupError:
  389. pass
  390. accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
  391. for accept_lang, unused in parse_accept_lang_header(accept):
  392. if accept_lang == '*':
  393. break
  394. if not language_code_re.search(accept_lang):
  395. continue
  396. try:
  397. return get_supported_language_variant(accept_lang)
  398. except LookupError:
  399. continue
  400. try:
  401. return get_supported_language_variant(settings.LANGUAGE_CODE)
  402. except LookupError:
  403. return settings.LANGUAGE_CODE
  404. @functools.lru_cache(maxsize=1000)
  405. def parse_accept_lang_header(lang_string):
  406. """
  407. Parse the lang_string, which is the body of an HTTP Accept-Language
  408. header, and return a tuple of (lang, q-value), ordered by 'q' values.
  409. Return an empty tuple if there are any format errors in lang_string.
  410. """
  411. result = []
  412. pieces = accept_language_re.split(lang_string.lower())
  413. if pieces[-1]:
  414. return ()
  415. for i in range(0, len(pieces) - 1, 3):
  416. first, lang, priority = pieces[i:i + 3]
  417. if first:
  418. return ()
  419. if priority:
  420. priority = float(priority)
  421. else:
  422. priority = 1.0
  423. result.append((lang, priority))
  424. result.sort(key=lambda k: k[1], reverse=True)
  425. return tuple(result)